1

Below is the sample program to test the return by value

  1. Why the function local obj address and main local object has same address ??
  2. Why no constructor is called when object is returned by value ??
  3. 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()

  1. 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);
    }

Community
  • 1
  • 1
Jagan Arikuti
  • 365
  • 1
  • 2
  • 11
  • Always check your formatting in the preview! – crashmstr Aug 07 '15 at 19:33
  • 5
    The effect you're observing is caused by an optimization called (Named) Return Value Optimization, or Copy Elision. – dyp Aug 07 '15 at 19:35
  • @crashmstr Well that's a strange formatting problem with code blocks following lists o.O – dyp Aug 07 '15 at 19:37
  • 1
    Ad 4) In that case, you won't get any advantage from using `std::move`. See, for example, http://stackoverflow.com/q/17473753/ -- when returning local variables or parameters, the compiler tries to apply NRVO (which is cheapest, because the `return` becomes a no-op), or if that's not possible, tries to use move semantics. For this, the return statement must be of the form `return variable_name;` Hence, `return std::move(variable_name);` is actually worse, since it doesn't allow NRVO. – dyp Aug 07 '15 at 21:16

0 Answers0