【问题标题】:Is `unique_ptr::operator bool()` defined for a unique_ptr that has been move()d from?`unique_ptr::operator bool()` 是否为已从中移动()的 unique_ptr 定义?
【发布时间】:2016-08-12 11:44:45
【问题描述】:

据我了解,从标准库对象移出后,该对象处于有效但未定义的状态。但在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;
}

输出:

p1 owns an object
p2 owns an object

【问题讨论】:

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


    【解决方案1】:

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

    这意味着状态或从unique_ptr 移出的状态不仅仅是有效的,它是定义的。

    【讨论】:

      【解决方案2】:

      我可以依靠这个吗?

      是的,你可以。继续std::unique_ptr 意味着从它转移所有权,然后operator bool 将返回false,因为它不拥有任何对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-07
        • 2018-07-11
        • 2015-04-15
        • 1970-01-01
        相关资源
        最近更新 更多