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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With