Below is the sample program to test the return by value
- Why the function local obj address and main local object has same address ??
- Why no constructor is called when object is returned by value ??
Why not yellow object destructor is not called in function while red object is destructor is called
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; }
Output
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()
As discuessed in What are copy elision and return value optimization? : if this is with named return value optimization - then what is the advantage we get if we return in function with move semantic
Demo fun() {
Demo d;
return std::move(d);
}