`unique_ptr::operator bool()` 是否为从 move()d 中移动的 unique_ptr 定义?
Is `unique_ptr::operator bool()` defined for a unique_ptr that has been move()d from?
据我了解,在我从标准库对象移出后,该对象处于有效但未定义的状态。但是在 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
unique_ptr
的规范明确指出,移动操作对此类指针的影响是所有权的转移 从右侧指针到左侧-手边指针(20.8.1/16 用于移动构造函数,20.8.1.2.3/2 用于赋值)。 transfer of ownership 的概念在标准 (20.8.1/4) 中明确定义,它表示右侧变为 nullptr在这样的转移之后。
这意味着状态或移出 unique_ptr
不仅有效,而且 已定义。
can I rely on this?
是的,你可以。在 std::unique_ptr
上移动意味着从它转移所有权,然后 operator bool
肯定会 return false
因为它不拥有任何对象。
据我了解,在我从标准库对象移出后,该对象处于有效但未定义的状态。但是在 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
unique_ptr
的规范明确指出,移动操作对此类指针的影响是所有权的转移 从右侧指针到左侧-手边指针(20.8.1/16 用于移动构造函数,20.8.1.2.3/2 用于赋值)。 transfer of ownership 的概念在标准 (20.8.1/4) 中明确定义,它表示右侧变为 nullptr在这样的转移之后。
这意味着状态或移出 unique_ptr
不仅有效,而且 已定义。
can I rely on this?
是的,你可以。在 std::unique_ptr
上移动意味着从它转移所有权,然后 operator bool
肯定会 return false
因为它不拥有任何对象。