1

I am executing the following code C++ code on

(Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

class x {
    public :
    int data ;
    x(int v) {cout<<"1 args constr\n" ; data = v ;}
    x(const x& o) {cout<<"copy constr\n" ;}
    x &operator=(const x&o) {cout<<"assignment opr\n" ;}
    ~x() {cout<<"destr\n" ;}
} ;

x fun() {
    cout<<"in func\n" ;   //#1
    x o(-19) ;            //#2
    cout<<"returning...\n";
    return o ;            //#3
}

main() {
    x ob = fun() ;        //#4
    cout<<ob.data<<endl ;
}

And getting the following output: in func 1 args constr returning... -19 destr

What I am not able to understand is :

  1. why are the constructor and destructor called ony once
  2. why is the copy constructor not invoked when I am returning by value

As per my understanding, ob is created in the scope of main. Thus the constructor and destructor for ob should be called in the scope of main. Likewise, o is created in the scope of fun. And thus there should be one constructor and destructor invocation for o in the scope of fun

user3282758
  • 1,379
  • 11
  • 29
  • x &operator=(const x&o) {cout<<"assignment opr\n" ;} bug here fix the operator overloading definition – Hariom Singh Oct 13 '17 at 04:58
  • Read about the [rule of five](http://en.cppreference.com/w/cpp/language/rule_of_three) – Basile Starynkevitch Oct 13 '17 at 05:11
  • @ Basile Starynkevitch I am not compiling code for C++11. Even after adding the move semantics and compiling for C++11 I am getting the same output – user3282758 Oct 13 '17 at 05:18
  • The explanation of what you are seeing is copy elision or return value optimisation. Although you haven't asked what they are, I've marked this as a duplicate of a question asking about them - the answers to that question explain the type of effect you are seeing. – Peter Oct 13 '17 at 05:33

1 Answers1

1

C++ compiler is doing the return value optimization once compiled. Note return value optimization can't be done if any of the end-points of a function return the different named local variable. In your case, there is only end-point for the function(return statement). So C++ compiler performs a Return Value Optimization. Check this out: return_value_optimization

Community
  • 1
  • 1