答案
不需要
原因
编译器自动优化,会直接在函数调用处构造该对象。
#include <iostream>
using namespace std;
class TestMove{
public:
TestMove(){
cout<<"Constructor"<<endl;
}
TestMove(const TestMove &&other){
cout<<"Move constructor"<<endl;
}
TestMove(const TestMove &other){
cout<<"Copy constructor"<<endl;
}
~TestMove(){
cout<<"Deconstrcutor"<<endl;
}
};
TestMove func(){
cout<<"no Move"<<endl;
TestMove testMove;
cout << "func::TestMove:" << &testMove << endl;
return testMove;
}
TestMove func_with_move(){
cout<<"with move"<<endl;
TestMove testMove;
return std::move(testMove);
}
int main(){
TestMove tm1 = func();
cout << "main::tm1:" << &tm1 << endl;
cout<<endl;
TestMove tm2 = func_with_move();
cout<<endl;
return 0;
}
当直接返回时,发现函数内对象地址和接收对象地址一样,证明编译器优化会在接受对象处直接构造,甚至不需要调用移动构造。
当使用move时,会理所应当的调用移动构造,相比直接返回甚至更慢。