Are you trying to change the behavior of const_cast-ed, but the dynamically allocated persistent object is undefined?

For instance:

const int* pc = new const int(3); // note the const int* p = const_cast<int*>(pc); *p = 4; // undefined behavior? 

In particular, can the compiler ever optimize a bunch of- distributed *pc ?

If not, does an attempt to change *pc through p behavior undefined, and if so, why?

+6
source share
2 answers

Yes and yes. Why - because you are modifying the const object.

And a good point in const after new is that the code would be legal without it.

+4
source

const_cast from const to not const is safe if the original pointer was not const .

If the original pointer is const (as in the case of your example), then the behavior is undefined.

If you wrote

const int* pc = new int(3);

then you can drop const -ness pc .

+3
source

Source: https://habr.com/ru/post/988848/


All Articles