即使 class 仅由智能指针组成,我们是否应该 delclare/define 析构函数?
Should we delclare/define destructor even if the class is composed by only smart pointers?
class A{
public:
A():p(nullptr){};
private:
std::unique_ptr<B> p; // B is some class
};
当A的对象超出范围时,p消耗的内存space会自动移除。
我们是否应该像下面这样显式地编写析构函数?
~A(){
delete p;
}
这是多余的吗?
Should we explicitly write the destructor as below?
没有。智能指针的全部意义在于为您自动管理内存。
Is this redundant?
不,这是 未定义的行为 - 将执行 "double free"。即使你为 A
提供析构函数,p
的析构函数也会被调用。
class A{
public:
A():p(nullptr){};
private:
std::unique_ptr<B> p; // B is some class
};
当A的对象超出范围时,p消耗的内存space会自动移除。
我们是否应该像下面这样显式地编写析构函数?
~A(){
delete p;
}
这是多余的吗?
Should we explicitly write the destructor as below?
没有。智能指针的全部意义在于为您自动管理内存。
Is this redundant?
不,这是 未定义的行为 - 将执行 "double free"。即使你为 A
提供析构函数,p
的析构函数也会被调用。