在 C++ 中,堆栈分配的对象可以声明为 const
:
const Class object;
之后尝试在此类对象上调用非常量方法是未定义的行为:
const_cast<Class*>( &object )->NonConstMethod(); //UB
堆分配的对象可以是 const
并产生相同的后果吗?我的意思是有可能出现以下情况:
const Class* object = new Class();
const_cast<Class*>( object )->NonConstMethod(); // can this be UB?
也是未定义的行为吗?
最佳答案
是的。构造和销毁 const
堆对象是合法的。与其他 const
对象一样,将其作为非 const
对象进行操作(例如,通过指针或引用的 const_cast
)会导致未定义的行为。
struct C
{
C();
~C();
};
int main()
{
const C* const p = new const C;
C* const q = const_cast<C*>(p); // OK, but writes through q cause UB
// ...
delete p; // valid, it doesn't matter that p and *p are const
return 0;
}
关于c++ - 在 C++ 中,堆分配的对象可以是 const 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1927477/