Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 547
Lmn Avatar asked Jun 10 '15 12:06

Lmn


People also ask

Is const_cast undefined behavior?

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior. So yes, modifying constant variables is undefined behavior.

What is the use of const_cast?

const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.

Can const pointer be deleted?

E2158 Operand of 'delete' must be non-const pointer (C++) It is illegal to delete a variable that is not a pointer. It is also illegal to delete a pointer to a constant.


2 Answers

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.

like image 199
Luchian Grigore Avatar answered Oct 12 '22 14:10

Luchian Grigore


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.

like image 3
Bathsheba Avatar answered Oct 12 '22 14:10

Bathsheba