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在线编译器中,它在第
coutautonpt=move(pt)行崩溃代码>将pt
的所有权转让给npt
离开pt
anullptr
。既然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();
}