Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is a copy before assign?

Tags:

c++

I am doing the following test:

#include <iostream>
#include <vector>

using namespace std;
class A
{
private:
   int i;
public:
   A():i(1){cout<<"A constr"<<endl;}
   A(const A & a):i(a.i){cout<<"A copy"<<endl;}
   virtual ~A(){cout<<"destruct A"<<endl;}
   void operator=(const A a){cout<<"A assign"<<endl;}
};


int main()
{
   A o1; 
   A o2; 
   o2=o1;
}

And the output is:

A constr
A constr
A copy
A assign
destruct A
destruct A
destruct A

It seems that "o2=o1" did a copy first followed by an assignment, and I wonder what's the story behind it. Thanks!

like image 828
Hailiang Zhang Avatar asked Mar 21 '12 14:03

Hailiang Zhang


1 Answers

Because you pass by value into your assignment operator:

void operator=(const A a)

You probably meant to pass by reference and you should also return a reference to the assigned-to object:

A& operator=(const A& a) { std::cout << "A assign" << std::endl; return *this; }
like image 134
CB Bailey Avatar answered Oct 20 '22 17:10

CB Bailey