Jue*_*gen 2 c++ destructor heap-memory unique-ptr
假设我们有一个简单的结构体,在 hpp 文件中有一个唯一的指针:
struct SomeType
{
SomeType() = default;
~SomeType();
std::unique_ptr<int> ptr;
};
Run Code Online (Sandbox Code Playgroud)
在 cpp 中我们有:
SomeType::~SomeType()
{
ptr.reset();
}
Run Code Online (Sandbox Code Playgroud)
这个析构函数是有用的还是多余的?是否有可能对内存/堆产生双重删除或其他不需要的副作用?
如果这是析构函数中唯一的一行代码,那么它是不必要的,无论哪种方式都会发生。所有成员析构函数都会在父析构函数之后自动调用。
如果您在析构函数中还有其他一些事情要做并且/或操作的确切顺序很重要,那么它可能会很有用。
不会发生双重删除。