Is an attempt to modify a const_cast-ed, but dynamically allocated constant object still undefined behavior? [duplicate]
Asked Answered
D

2

6

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?

Detta answered 10/6, 2015 at 12:20 Comment(3)
It's an interesting question but why would you do that?Mariomariology
related - #22799058Portwine
const_cast should only be used for interfacing with code that is const-incorrect, for example a function that doesn't modify a string but still takes a char* instead of const char*. Any other kind of use where you modify the object is undefined behaviorCycloid
P
4

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.

Portwine answered 10/6, 2015 at 12:23 Comment(0)
B
3

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.

Budget answered 10/6, 2015 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.