以下是测试按值返回的示例程序
为什么在红色对象被析构函数被调用时不会在函数中调用黄色对象析构函数
class Demo
{
string s_name;
public:
Demo()
{
cout << s_name << "Default constructor " << endl;
}
Demo(string name):s_name(name){
cout << s_name << " in Demo::Demo(string)" << endl;
}
Demo(Demo && p){
cout << s_name << " in Demo::Demo( && )" << endl;
s_name=p.s_name;
}
Demo(Demo const & p){
cout << s_name << " in Demo::Demo( && )" << endl;
}
~Demo() {
cout << s_name << " in Demo::~Demo()" << endl;
}
const string & getname(){ return s_name;};
};
Demo fun() {
Demo a("Red"),b("Yellow");
cout << b.getname() << " Addres of in fun " << &b << endl <<endl;
return b;
}
int main() {
Demo obj = fun();
cout << endl << obj.getname() << " Addres of in main " << &obj << endl << endl;
return 0;
}
Red in Demo::Demo(string)
Yellow in Demo::Demo(string)
Yellow Addres of in fun 0x7342d7c3b7f0
Red in Demo::~Demo()
Yellow Addres of in main 0x7342d7c3b7f0
Yellow in Demo::~Demo()
正如What are copy elision and return value optimization?中所述:如果这是带有命名的返回值优化 - 那么如果我们使用移动语义返回函数,我们获得的优势是什么
Demo fun(){
演示d;
return std :: move(d);
}