unique_ptr 的多重赋值有效吗?

Are multiple assignments to unique_ptr valid?

unique_ptr<T> 的多次赋值是否有效?根据输出,它是,但是 T 的析构函数保证在使用 make_unique() 并且 return 值分配给已经持有的 unique_ptr 时被调用现有内存?

#include <iostream>
#include <string>
#include <memory>

class A{
public:
    A(){ std::cout << "Construcor" << std::endl; }
    ~A(){ std::cout << "Destrucor" << std::endl; }
    void foo(){ std::cout << "foo" << std::endl; }
};

int main()
{
    std::unique_ptr<A> pointer;
    for(auto i = 0; i < 2; ++i){
        pointer = std::make_unique<A>();
        pointer->foo();
    }
}

输出:

Construcor
foo
Construcor
Destrucor // Destructor is called because first instance of A is out of scope?
foo
Destrucor

是的,完全正确。

当您将新对象分配给 unique_ptr 时,它会销毁其当前对象并取得新对象的所有权。这是预期的记录行为。

正如您在日志记录中看到的那样,这正是实际发生的情况:

Construcor   (first call to make_unique) 
             (first assignment, nothing to log here) 
foo
Construcor   (second call to make_unique)
Destrucor    (second assignment, first object destroyed)
foo
Destrucor    (main exits, second object destroyed)