在下面的代码中,输出结果为空白,而不是构造函数和析构函数的打印输出。没有移动操作,代码运行良好。我不知何故弄乱了移动操作,请仔细检查并提供您的意见以进一步指导。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
template <class T>
class smart{
public:
smart():pt{nullptr}{
}
smart(T *ptr):pt{ptr}{
}
T *pt;
smart(const smart& ob)=delete;
smart operator=(const smart& ob)=delete;
smart (smart&& dyingob){
this->pt=dyingob.pt;
dyingob.pt=nullptr;
}
void operator=(smart&& dyingob){
pt=dyingob.pt;
dyingob.pt=nullptr;
}
T* operator ->(){return this->pt;};
~smart(){
if(pt!=nullptr)
delete pt;
}
};
class A{
public:
A(int n){
data=n;
cout<<"\nconstructed";
}
~A(){
cout<<"\ndestructed";
}
int data;
};
int main()
{
smart<A> ob(new A(5));
smart<A> ob1;
ob1=(std::move(ob));
cout<<ob->data;
return 1;
}
当注意到意外行为时,首先要检查的是编译器警告。但是 - 也许没有非常具体的标志 - 你不太可能在这里得到这些。
但是,要检查的第二件事是“静态分析工具”告诉您有关程序的信息。让我们尝试一下 clang-tidy
(版本 14),例如:
1 warning generated.
/tmp/a.cpp:51:11: warning: Method called on moved-from object 'ob' [clang-analyzer-cplusplus.Move]
cout<<ob->data;
^~~~
/tmp/a.cpp:50:4: note: Object 'ob' is moved
ob1=(std::move(ob));
^~~~~~~~~~~~~~~~~~~
/tmp/a.cpp:51:11: note: Method called on moved-from object 'ob'
cout<<ob->data;
^~~~
所以,你正在对一个移出的对象进行操作(就像评论者也告诉你的那样......例如@songyuangyo)。
ob->data
是移动后的
nullptr
,不是吗?