如果我为类thing
定义了一个使用传值方式调用复制构造函数的复制赋值运算符:
thing& operator= (thing x) {
为同一类添加移动赋值运算符:
thing& operator= (thing&& x) {
尝试调用移动赋值会导致gcc出现错误:
error: ambiguous overload for ‘operator=’ (operand types are ‘thing’ and ‘std::remove_reference<thing&>::type {aka thing}’)
然而,如果复制赋值运算符使用的是引用传递:
thing& operator= (thing& x) {
编译通过,两个操作符都可以调用。为什么呢?
C++11完整测试代码:
#include <iostream>
#include <utility>
using namespace std;
class thing {
public:
thing () { }
thing (thing& x) {
cout << "Copy constructor.\n";
}
thing (thing&& x) {
cout << "Move constructor.\n";
}
thing& operator= (thing x) {
cout << "Copy assign using pass by value.\n";
return *this;
}
thing& operator= (thing&& x) {
cout << "Move assign.\n";
return *this;
}
};
int main (void) {
thing a, b;
// Invoke move assignment:
a = move(b);
return 0;
}
A
的右值更倾向于绑定到A&&
而不是A&
。对于A&&
与A
之间没有相应的规则。 - T.C.A&
不必须是 lvalue 吗? - CodeClown42const A&
。A&
只绑定左值。 - T.C.