```
Class A {
....
....
..
/// option A
~A() = default
/// option B
~A() {
///destructor code here
}
}
```
假设我使用了定义了自己的解构函数的选项B,当指针指向持有上述类的对象时,我会执行类似
的操作objAPtr = nullptr;
析构函数被调用了吗?还是上述仅适用于选项B
我在这里使用智能指针:
objAPtr = make_shared<A>();
答案 0 :(得分:4)
如果您有
A* objAPtr = new A;
objAPtr = nullptr;
然后否,objAPtr
指向的对象将不被破坏。取而代之的是,您将失去对该对象的唯一引用,这将是一个泄漏。
这与无关与您拥有的“哪种”析构函数有关。
答案 1 :(得分:1)
否,通过将指向对象的指针设置为nullptr
不会自动调用析构函数。调用析构函数的时间和方式不仅与是否= default
声明正交,还取决于环境以及如何分配用于保存A
实例的内存。堆栈上有一个A
实例的示例:
{
A aInstance;
A *somePointerToA = &aInstance;
somePointerToA = nullptr; // aInstance not touched, only the pointer to it.
} // aInstance goes out of scope, now the destructor is called.
并且在堆上创建时:
auto *aInstance = new A;
a *somePointerToA = aInstance;
somePointerToA = nullptr; // aInstance again untouched.
delete aInstance; // Now the destructor is called.
使用智能指针管理实例时,这些语义会发生变化,这可以解决破坏问题。示例:
#include <memory>
auto aInstance = std::make_unique<A>();
aInstance = nullptr; // The std::unique_ptr calles A's destructor
auto aSharedInstance = std::make_shared<A>();
auto anotherSharedInstance = aSharedInstance;
aSharedInstance = nullptr; // dtor not called because of anotherSharedInstance
anotherSharedInstance = nullptr; // last pointer to the instance, dtor is called
答案 2 :(得分:0)
是的,在将变量设置为nullptr或进行重置时也会调用析构函数:
class Test
{
private:
int m_nID;
public:
Test(int nID)
{
std::cout << "Constructing Test " << nID << '\n';
m_nID = nID;
}
~Test()
{
std::cout << "Destructing Test " << m_nID << '\n';
}
int getID() { return m_nID; }
};
int main()
{
// create a shared pointer
auto pTest = std::make_shared<Test>(1);
std::cout << pTest->getID() << '\n';
// Allocate a Test dynamically
auto pTest2 = std::make_shared<Test>(2);
std::cout << pTest2->getID() << '\n';
pTest = nullptr;
//pTest.reset();
std::cout << "before sleep \n ";
sleep(5);
return 0;
} // Test goes out of scope here
在析构函数上方运行时,将其设置为nullptr。
编译选项
g++ def_destr.cpp -std=c++14