右值引用主要是为了优化。
在函数返回值没有打开-fno-elide-constructors时,函数返回值会调用拷贝构造函数
class X
{
public:
X()
{
cout << "X ctor" << endl;
}
X(const X& x)
{
cout << "X copy ctor" << endl;
}
~X()
{
cout << "X dtor" << endl;
}
};
X makeX()
{
X x1;
return x1;
}
int main()
{
X x = makeX();
return 0;
}
参数是右值引用,如果传的参数是左值,会编译不通过
void printName(string&& name)
{
cout << name << endl;
}
int main()
{
string firstName = "wang", lastName = "wenhao";
string fullName = firstName + lastName;
printName(fullName);
return 0;
}
需要改成printName(firstName + lastName)