【问题标题】:Are multiple assignments to unique_ptr valid?对 unique_ptr 的多个分配是否有效?
【发布时间】:2019-01-30 20:32:25
【问题描述】:

unique_ptr<T> 的多次分配是否有效?根据输出,它是,但是T 的析构函数是否保证在使用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();
    }
}

输出:

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

【问题讨论】:

  • unique_ptr 的实例分配给另一个实例将替换前一个实例,这需要正确销毁先前保存的值(如果存在)。其他任何东西都会泄漏。

标签: c++ c++11 unique-ptr


【解决方案1】:

是的,它完全有效。

当您将新对象分配给 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) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多