当指针在 cpp 17 中失去引用时,是否会调用非默认析构函数?

Does the non default destructor be called when a pointer goes out of reference in cpp 17?

本文关键字:调用 是否 默认 析构函数 cpp 指针 引用 失去      更新时间:2023-10-16

'''

Class A {
....
....
..
/// option A
~A() = default 
/// option B
~A() {
///destructor code here
}
}

'''

假设我使用选项 B,其中我定义了自己的解构函数,当指针指向持有上述类的对象时,我执行类似操作

objAPtr = nullptr;

是否调用析构函数? 还是上述内容仅适用于选项 B

我在这里使用智能指针:

objAPtr = make_shared<A>();

如果你有例如

A* objAPtr = new A;
objAPtr = nullptr;

那么不,objAPtr指向的对象不会被破坏。相反,您将丢失对该对象的唯一引用,并且它将是泄漏。

这与你拥有的析构函数的"种类"无关。

不,析构函数不会通过设置指向对象的指针来自动调用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

是的,在将变量设置为 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