C++ 移动后使用唯一的_ptr

C++ 移动后使用唯一的_ptr,c++,move-semantics,unique-ptr,C++,Move Semantics,Unique Ptr,我不明白为什么这个代码会起作用: class Base { public: virtual void doStuff() const{} Base(Base & b) = delete; Base() { cout << "Base" << endl; } ~Base() { cout << "~Base" << endl; } friend ostre

我不明白为什么这个代码会起作用:

class Base {
public:
    virtual void doStuff() const{}
    Base(Base & b) = delete;
    Base() {
        cout << "Base" << endl;
    }
    ~Base() {
        cout << "~Base" << endl;
    }
    friend ostream& operator<<(ostream& out, const Base& a) {
         return out << "me";
    }
};
int main(){
    unique_ptr<Base> pt = make_unique<Base>();
    auto npt = move(pt);
    auto &a = *pt;

    if (pt == nullptr)
        cout << "yes nullptr" << endl;
    cout << a << endl;
}
因此,它不会崩溃,
pt
甚至可以在从移动后使用。
在coliru在线编译器中,它在第
cout
autonpt=move(pt)行崩溃
pt
的所有权转让给
npt
离开
pt
a
nullptr
。既然
pt
现在是
nullptr
那么
if(pt==nullptr)首先

auto &a = *pt;
是一种未定义的行为,未定义。在C++中取消A<代码> NulLPTR <代码>不会使程序崩溃,它可能发生一切。


您可能期望从代码中得到的是a,但它不会发生,因为您实际上从未访问对象
a


实际上,您的
运算符undefined行为是未定义的。您忘记了您的
运算符,因此它不会崩溃,
pt
甚至可以在从中移动后使用。谁说它总是会崩溃?这是未定义的行为;库特
auto &a = *pt;
friend ostream& operator<<(ostream& out, const Base& a) {
     a.do_stuff();
}