In C++ it is possible to allocate a const object on heap:
const Class* object = new const Class();
const_cast<Class*>( object )->NonConstMethod(); // UB
so that attempt to write into an object will be UB.
I don't get how such an object will be different from a heap-allocated object that is not declared const
:
const Class* object = new Class();
I mean when I allocate an object on stack it goes to automatic storage which is implementation-specific and so there might be some implementation-specific means that would allow allocating const
objects in some special way that would yield UB when I write to an object.
Yet whenever I use new
the compiler is required to emit operator new()
function invokation and that function can't possibly do anything different - it just allocates memory in a uniform manner regardless of whether there was const
in my code.
How is a const
heap-allocated object different from a non-const
one and how is undefined behavior possible if I try to modify it?