c++ - 在 C++ 中,堆分配的对象可以是 const 吗?

标签 c++ constants const-correctness undefined-behavior

在 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/

相关文章:

c++ - `*' 不能出现在常量表达式中

c++ const 使用。我可以删除它吗?

c++ - 智能指针的 const 正确性

c++ - 共享指针和 const 正确性

c++ - 向我推销 const 正确性

c++ - 最大化 tensorflow 多 GPU 性能

双重包含的C++/SDL问题

c# - 只读值的优雅解决方案

c++ - 未解析的外部符号 - C++

C++前向声明问题