![](/img/trans.png)
[英]Reassigning a pointer when the object it is pointing to is deleted by an instance of another class
[英]Does the pointer in a class get deleted when the class gets deleted/destroyed?
我是 C++ 的新手,我想知道,当 class 被删除/销毁时,指针是否会自动删除? 这是一个例子:
class A
{
public:
Object* b;
};
当 class 被删除时, b
会被删除吗?
指针指向的object不会被删除。 That is why it is a bad idea to use a raw pointer to refer to an object created with dynamic storage duration (ie via new
) like this if the class object is intended to be responsible for destroying that object. 而是使用std::unique_ptr
:
#include<memory>
//...
class A
{
public:
std::unique_ptr<Object> b;
};
而不是new Object(/*args*/)
使用std::make_unique<Object>(/*args*/)
来创建 object 和指向 object 的智能指针以存储到b
。
或者,最有可能的是,根本没有理由使用指针间接。 您可以直接在 class 中拥有Object
。 (如果Object
是多态的,这真的不起作用。)
为指针本身保留的 memory 被释放,因此从这个意义上说, b 被“删除”。 但是,如果在 b 被删除之前 b 未设置为 nullptr(b 点适当处理的任何 object),那么您可能会遇到 memory 泄漏。
综上所述:当object被销毁时,指针本身会被删除,而指针指向的object则不会发生任何事情。 您将需要创建一个适当的析构函数来处理此问题。
不,原因很简单,没有说指针用于分配数据:构造函数中没有隐式的new
,也许指针根本不用于动态分配,而是用于其他目的。
一个额外的原因是,在您的用例中,可能不希望删除指向的数据,例如,这些数据可能会在其他地方共享。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.