gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:01:33 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com