私は、標準ライブラリオブジェクトから移動した後、そのオブジェクトが有効であるが未定義の状態にあることを理解しています。しかし、unique_ptr
の場合、それはどのように定義されていませんか?経験的には、以下のコードは動作するようです。つまり、p1
から移動した後、 "if (p1)
"はfalseを評価します。直観的には、これは正しい動作のようです。しかし、私はこれに頼ることができますか?unique_ptr :: operator bool()はmove()dからのunique_ptrに対して定義されていますか?
#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