struct copyable { // and movable
copyable() = default;
copyable(copyable const&) { /*...*/ };
copyable& operator=(copyable const&) { /*...*/ return *this; }
};
Run Code Online (Sandbox Code Playgroud)
由于复制构造函数和复制赋值操作函数是显式定义的,因此它表示编译器不能隐式定义移动构造函数和移动赋值函数,因此不允许移动操作.
能告诉我上述理解是否正确吗?
#include<iostream>
#include<stdio.h>
using namespace std;
class Test
{
public:
string n;
Test():n("test") {}
};
int main()
{
Test t1;
std::cout<<"before move"<<"\n";
std::cout<<"t1.n=" << t1.n<<"\n";
Test t2=std::move(t1);
std::cout<<"after move"<<"\n";
std::cout<<"t1.n="<<t1.n<<"\n";
std::cout<<"t2.n="<<t2.n<<"\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上述程序的输出产生以下结果
移动前 t1.n=测试 移动后 t1.n= t2.n=测试
了解到,将对象 t1 移动到 t2 后,t2.n 的值结果为空字符串
但相同的概念移动概念不适用于整数。
#include<iostream>
#include<stdio.h>
using namespace std;
class Test
{
public:
int n;
Test():n(5) {}
};
int main()
{
Test t1;
std::cout<<"before move"<<"\n";
std::cout<<"t1.n=" << t1.n<<"\n";
Test t2=std::move(t1);
std::cout<<"after move"<<"\n";
std::cout<<"t1.n="<<t1.n<<"\n";
std::cout<<"t2.n="<<t2.n<<"\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上述程序的输出产生以下结果 …