【发布时间】: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