`unique_ptr :: operator bool()`是为来自move()d的unique_ptr定义的吗?

Joh*_*uld 2 c++ unique-ptr c++-standard-library move-semantics c++11

我的理解是,在从标准库对象移动后,该对象处于有效但未定义的状态.但是在a的情况下,unique_ptr它是多么不确定?根据经验,下面的代码似乎有效,也就是说,在我离开后p1," 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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

p1 owns an object
p2 owns an object
Run Code Online (Sandbox Code Playgroud)

AnT*_*AnT 7

unique_ptr规范明确指出移动操作对这些指针的影响是所有权从右侧指针转移到左侧指针(移动构造函数为20.8.1/16,20.8.1.2.3/2)为了分配).所有权转让的概念在标准(20.8.1/4)中明确规定,并且表明在转移后右侧变为nullptr.

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