对unique_ptr<T>
的多个分配有效吗?基于输出,可以肯定,但是使用T
并将返回值分配给已经保存了现有内存的make_unique()
时,是否保证调用unique_ptr
的析构函数?< / p>
#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
答案 0 :(得分:3)
是的,它是完全有效的。
将新对象分配给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)