有类型声明的时候,不管有没有等号都是构造,之前定义过用等号接收的就是赋值。接收的是右值就是移动构造或移动赋值,接收左值就是拷贝构造或拷贝赋值。跟编译器无关,当然还是要支持移动语义的(C++11),下面是举例:
#include <stdio.h>
#include <type_traits>
struct A {
int value;
A() : value(0) {}
A(int v) : value(v) {}
A(const A& o) {
value = o.value;
printf("copy constructor\n");
}
A(A&& o) noexcept {
value = o.value;
o.value = 0;
printf("move constructor\n");
}
A& operator=(const A& o) {
value = o.value;
printf("copy assignment operator\n");
return *this;
}
A& operator=(A&& o) noexcept {
if (this != &o) {
value = o.value;
o.value = 0;
}
printf("move assignment operator\n");
return *this;
}
};int main() {
A x(1), y(2); // 默认的构造
printf("case 1:"); A a(x); // 拷贝构造
printf("case 2:"); A b = x; // 拷贝构造,虽然有等号,但因为有类型定义,所以还是构造
printf("case 3:"); a = y; // 拷贝赋值,因为a前面定义了
printf("case 4:"); A c; c = A(); // 移动赋值,因为接收的临时右值A()
printf("case 5:"); A d(std::move(a)); // 移动构造,因为接收的左值a强转的右值,这句后面代码不能再用a,a的内容由d接管
printf("case 6:"); A e = std::move(b); // 移动构造,因为接收的左值b强转的右值,这句后面代码不能再用b,b的内容由e接管
printf("case 7:"); A f; f = std::move(c); // 移动赋值,因为接收的左值c强转的右值,这句后面代码不能再用c,c的内容由f接管
return 0;
}
额外细节:
其中,std::move的作用就是将左值对象强转为右值,不能再使用了。(所谓右值,就是临时对象,生命周期只在代码的当前行)
AA a ;
function(std::move(a)); //这里其实就是生成了一个右值a',并且调用a的移动构造(具体细节在移动构造函数中实现),a不应该再使用。但a这时其实生命周期还在,从代码上讲你还是可以使用它,但这是你要注意,a内部的某些变量可能不能再使用了。
为什么int &r = 3会报错呢?而const int &r =3不会报错?
实际move发生的细节是由移动函数实现的。