Is an attempt to modify a const_cast-ed, but dynamically allocated constant object still undefined behavior?

151 views Asked by At

For example:

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 away the heap-allocated *pc?

If not, does an attempt to modify *pc via p still constitute undefined behavior - and if so, why?

2

There are 2 answers

0
Luchian Grigore On BEST ANSWER

Yes and yes. As to why - because you're modifying a const object.

And good point about the const after new - without it, the code would be legal.

0
Bathsheba On

const_cast from const to non-const is only safe if the original pointer was non-const.

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

If you had written

const int* pc = new int(3);

then you could cast away the const-ness of pc.