c++ - why compiler is not eliding away copy construction in this case -


class test {  public:      int data;     test(int var = 0):data(var){cout<<"constructor"<<endl;}     ~test(){ cout<<"destructor"<<endl; }      test(const test& var)     {         cout<<"copy constructor"<<endl;         this->data = var.data;      }     test& operator=( const test& var)     {         cout<<"assignment op"<<endl;         this->data = var.data;         return *this;     }  };   test passbyref_returnbyval(test& obj)     {         return obj;     }   int main() {      test o1(5);     test o2 = passbyref_returnbyval(o1);     cout<<"=========================="<<endl;     test o3;     o3 = passbyref_returnbyval(o1);    } 

output:

constructor  copy constructor  constructor  copy constructor  assignment op  destructor 

in given example , object o2 directly copy constructed without using temporaries.

but in second case want o3 assigned return value of function, first temporary created using copy constructor , assignment operator called value assignment.

my question need temporary assignment operator takes reference. found related questions didnt answer this.

test o3; 

will cause call constructor create object. c++ isn't java object type declaration declares references doesn't instantiate object.

test passbyref_returnbyval(test& obj) {....} 

causes copy constructor call because when inside of return obj; compiler needs create temporary object because return type of function test (as opposed test& or test*).

finally, because o3 exists courtesy of the

test o3; 

declaration, assignment operator called assign return value of passbyref_returnbyval already-existing o3.

so copy constructor call happening in passbyref_returnbyval, not in operator=.


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c++ - Using OpenSSL in a multi-threaded application -

All overlapping substrings matching a java regex -