堆分配的对象可以是C ++中的const吗? [英] Can a heap-allocated object be const in C++?

查看:140
本文介绍了堆分配的对象可以是C ++中的const吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,可以将堆栈分配的对象声明为 const

In C++ a stack-allocated object can be declared const:

const Class object;

之后尝试调用此类对象上的非const方法是未定义的行为:

after that trying to call a non-const method on such object is undefined behaviour:

const_cast<Class*>( &object )->NonConstMethod(); //UB

堆分配的对象可以是 const 有同样的后果?我的意思是有可能如下:

Can a heap-allocated object be const with the same consequences? I mean is it possible that the following:

const Class* object = new Class();
const_cast<Class*>( object )->NonConstMethod(); // can this be UB?

也是未定义的行为?

推荐答案

是的。构建和销毁一个 const 堆对象是合法的。与其他 const 对象一样,将其作为非< - code> const 对象进行操作的结果(例如通过 const_cast 的指针或引用)会导致未定义的行为。

Yes. It's legal to construct and destroy a const heap object. As with other const objects, the results of manipulating it as a non-const object (e.g. through a const_cast of a pointer or reference) causes undefined behaviour.

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 ++中的const吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆