这怎么可以编译? (删除const对象的成员) [英] How can this compile? (delete a member of const object)

查看:144
本文介绍了这怎么可以编译? (删除const对象的成员)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Test $ b $ 

b {
public:
Test()
{
p = new int(0);
}

Test(const Test& t)
{
delete t.p。 //我期望这里有一个错误
}

〜Test()
{
delete p;
}

private:
int * p;
};


解决方案

不改变 p 本身(因为 p 保持不变,因为你不改变它的值)重新改变 p 指向并因此在一个附加级别的间接工作。这是可能的,因为删除与指针相关联的内存不会改变指针本身。



严格意义上,对象的常量被保留,即使 c>



正如JonH提到的那样,它的逻辑常数已经被违反了,在注释中,如果你不能删除由const对象保存的指针指向的对象,那么你将会遇到内存泄漏,因为你无法在对象后正确清理。


I would expect an error inside the copy constructor, but this compiles just fine with MSVC10.

class Test
{
public:
    Test()
    {
        p = new int(0);
    }

    Test(const Test& t)
    {
        delete t.p; // I would expect an error here
    }

    ~Test()
    {
        delete p;
    }

private:
    int* p;
};

解决方案

The issue that you are running into here is that you are not changing p per se (thus pstays immutable as you're not changing its value), but you're changing what p points to and thus are working at one additional level of indirection. This is possible because deleteing the memory associated with a pointer doesn't change the pointer itself.

In a strict sense the const-ness of the object is preserved, even though its logical constness has been violated as you pulled the rug from underneath whatever p was pointing to.

As JonH mentioned in the comment, if you were not able to delete the object pointed to by a pointer held in a const object, you would end up with memory leaks because you wouldn't be able to clean up properly after the object.

这篇关于这怎么可以编译? (删除const对象的成员)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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