#include <iostream>
using namespace std;
class Test {
public:
Test(string value){
cout<<"Ctor "<<value<<endl;
_val=value;
}
Test( Test&& mv): _val(mv._val)
{
mv._val=string();
cout<<"Mv constructor"<<endl;
}
string& get()
{
return this->_val;
}
private:
string _val;
};
void print(Test&& t)
{
cout<<"Stampa val is "<<t.get()<<endl;
}
int main()
{
Test a{"ciao"};
print(move(a));
cout<<"Val of a is "<<a.get()<<endl;
print(Test("test"));
return 0;
}
其输出是(将行号添加到标准输出):
Ctor ciao
Stampa val is ciao
Val of a is ciao
Ctor test
Stampa val is test
为什么在 main 的第 2 行没有调用 mv 语义?我可能会在第四行理解有一个优化,所以只调用了构造函数,但是我无法解释第一步。有任何想法吗?