在C++中,可以声明堆栈分配的对象const:
const Class object;
Run Code Online (Sandbox Code Playgroud)
之后尝试在这样的对象上调用非const方法是未定义的行为:
const_cast<Class*>( &object )->NonConstMethod(); //UB
Run Code Online (Sandbox Code Playgroud)
堆分配的对象可以const具有相同的后果吗?我的意思是有可能是以下几点:
const Class* object = new Class();
const_cast<Class*>( object )->NonConstMethod(); // can this be UB?
Run Code Online (Sandbox Code Playgroud)
还是未定义的行为?