【问题标题】:Doing std::move twice with the same unique_ptr使用相同的 unique_ptr 执行两次 std::move
【发布时间】:2019-12-23 14:57:02
【问题描述】:

如果我用相同的 unique_ptr 调用 std::move 两次会发生什么?

unique_ptr<int> foo(new int(5));
unique_ptr<int> bar = move(foo);
unique_ptr<int> baz = move(foo);

PS:不,std::unique_ptr usage 不是同一个问题。这两个问题都是关于 unique_ptr 的,这是它们之间唯一的共同点。

【问题讨论】:

    标签: c++ move unique-ptr


    【解决方案1】:

    unique_ptr 移出时,它会保留为空。所以baz 最终也会为空。

    【讨论】:

      【解决方案2】:

      基本上,什么都没有。标准库要求移动库类型使其处于有效但未指定的状态。通过有效,它们意味着您仍然可以对不需要先决条件的对象执行操作。这就是给它分配一个新值或销毁它之类的事情。对于unique_ptr,我们实际上得到了更多的状态保证作为move constructor guarantees that the moved from object is set to nullptr。这意味着在所有这一切的末尾bar 持有指针,foobaz 都是nullptr

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-27
        • 2013-05-18
        • 2016-03-21
        • 1970-01-01
        • 2019-07-14
        • 1970-01-01
        • 2019-07-09
        • 1970-01-01
        相关资源
        最近更新 更多