unique_ptr资源设置为nullptr后如何释放?

How will a unique_ptr resource be freed after it is set to nullptr?

这是未定义的行为吗?如果指针指向无处,它如何删除分配的资源?

// Example program
#include <iostream>
#include <memory>

class A {
    public:
    A()  {std::cout << "ctor"<<std::endl;};
    ~A(){std::cout << "dtor"<<std::endl;};

};

int main()
{
    std::unique_ptr<A> ptr(new A);
    ptr = nullptr;

    return 0;
}

输出:

ctor
dtor

也许它是故意以这种方式创建的,以解决某种问题?

您正在调用 std::unique_ptr 赋值运算符 (operator=( nullptr_t ))。此运算符删除当前拥有的对象并将唯一指针设置为不拥有任何对象。如果你想释放对象的所有权以使其不被删除,有一个函数可以做到这一点。

ptr.release();

Perhaps it was created this way intentionally to solve some sort of problem?

是的,它旨在减少意外内存泄漏的情况,要求您在要释放对象所有权时(通过释放函数)明确说明。