-3 c++ unique-ptr c++11
多次赋值unique_ptr<T>
有效吗?根据输出,确实如此,但是当使用 且返回值被分配给已经持有现有内存的aT
时,是否保证调用 的析构函数?make_unique()
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();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Construcor
foo
Construcor
Destrucor // Destructor is called because first instance of A is out of scope?
foo
Destrucor
Run Code Online (Sandbox Code Playgroud)
是的,这是完全有效的。
当您将一个新对象分配给 a 时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)
Run Code Online (Sandbox Code Playgroud)