直接上测试代码:
#include <cstdio>#include <iostream>#include <string>class MyClass{int _a = 0;public:const int &a{_a};std::string temp;MyClass() = default;MyClass(const MyClass& another) : _a(another._a) {};friend int main();};int main(){MyClass cls1;cls1.temp = "233";cls1._a = 2;MyClass cls2 = std::move(cls1);cls2._a = 3;std::cout << cls1.a << " " << cls2.a << std::endl;std::cout << cls1.temp << " " << cls2.temp << std::endl;}运行结果:
2 3233说明调用的是复制构造函数(因为 a 这个引用(即指针)被赋值为了 cls2._a,且 cls1.temp 没有被复制,也没有被移动)。注释掉复制构造函数:
#include <cstdio>#include <iostream>#include <string>class MyClass{int _a = 0;public:const int &a{_a};std::string temp;MyClass() = default;// MyClass(const MyClass& another) : _a(another._a) {};friend int main();};int main(){MyClass cls1;cls1.temp = "233";cls1._a = 2;MyClass cls2 = std::move(cls1);cls2._a = 3;std::cout << cls1.a << " " << cls2.a << std::endl;std::cout << cls1.temp << " " << cls2.temp << std::endl;}运行结果:
2 2 233说明调用的是默认移动构造函数,即移动构造每一个成员变量(从 temp 可以看出成员变量的构造方式是移动构造,而 cls2.a 指向了 cls1._a 说明引用类型(指针类型)的移动构造是浅拷贝)。