c++ - `unique_ptr::operator bool()` 是否为已从 move()d move 的 unique_ptr 定义?

标签 c++ c++11 move-semantics unique-ptr c++-standard-library

据我了解,在我从标准库对象移出后,该对象处于有效但未定义的状态。但是在 unique_ptr 的情况下,它到底有多未定义?根据经验,下面的代码似乎有效,也就是说,在我从 p1 move 之后,“if ( p1 )” 的计算结果为 false。直觉上,这似乎是正确的行为。但是我可以依靠这个吗?

#include <memory>
#include <iostream>

int main( int argc, char* argv[] )
{
    using namespace std;

    unique_ptr<int> p1 {make_unique<int>(1)};
    unique_ptr<int> p2;

    if ( p1 )
        cout << "p1 owns an object" << endl;
    if ( p2 )
        cout << "p2 owns an object" << endl;

    p2 = move(p1);

    // Is the following test valid, now that p1 has been moved from?
    if ( p1 )
        cout << "p1 owns an object" << endl;
    if ( p2 )
        cout << "p2 owns an object" << endl;
}

输出:

p1 owns an object
p2 owns an object

最佳答案

unique_ptr 的规范明确指出, move 操作对此类指针的影响是从右侧指针到左侧的所有权转移指针(20.8.1/16 用于 move 构造函数,20.8.1.2.3/2 用于赋值)。 所有权转移的概念在标准 (20.8.1/4) 中明确定义,它表示在此类转移后右侧变为 nullptr

这意味着状态或移出 unique_ptr 不仅有效,而且是定义的

关于c++ - `unique_ptr::operator bool()` 是否为已从 move()d move 的 unique_ptr 定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36732917/

相关文章:

c++ - 将联盟重新解释为其他联盟

c++ - 重新调整 GLFW 窗口大小时渲染区域不会更改

c++ - Consexpr 数学函数

c++ - 强制返回的 const 值 move 而不是复制

c++ - 当 T 没有复制构造函数时,std::queue<T> 的虚拟包装器不编译

c++ - 无法调用指针的打印函数

c++ - 在 Visual Studio C++ 2010 中找不到或打开 PDB 文件

c++ - 如何从对象调用我的设置回调函数?

c++ - 如何从此指针获取 std::weak_ptr<MyClass> ?

c++ - 在基于范围的 for 循环中使用转发引用有什么好处?