I was using const_cast to modify elements inside an initializer_list, like below:
#include <initializer_list>
int main()
{
auto a1={1,2,3};
auto a2=a1;//copy or reference?
for(auto& e:a1)
{
int*p=const_cast<int*>(&e);
++(*p);
}
for(auto& e:a2)
cout<<e;
return 0;
}
Unfortunately, when doing ++(*p) this g++4.9.2 compiled program throws SIGSEGV. The problem doesn't happen in VC.
Why is that, is my program having any unsafe operations? Please help, thanks.
As I mentioned on your previous question, the underlying array for an initializer_list<T>
is composed on const
objects. Modifying objects declared const
is undefined behavior. From [dcl.type.cv]:
Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.
One possible instantiation of undefined behavior is SIGSEV, which is what you see from gcc. Another possible instantiation is the code working, which is what you see in VC. Just don't do it.