Hailiang Zhang
Hailiang Zhang

Reputation: 18930

Why there is a copy before assign?

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!

Upvotes: 6

Views: 182

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153955

You seem to set up you assignment operator to be implemented properly:

T& T::operator= (T value) {
    value. swap(*this);
    return *this;
}

The argument is passed by copy to the assigment operator and the compiler actually needed to do this copy in your set up. If you had passed a temporary the copy could have been avoided:

o2 = A();

Thus, the implementation above actually has a few interesting properties:

  • it leverages already written functions: the copy constructor is either generated or written but does the Right Thing and if you want to have an assignment you probably want to have swap() member as well
  • the assignment is strong exception safe if the swap() operation is non-throwing as it should be. When allocators enter the picture things need to be done slightly different, though
  • the assignment tries to avoid actual copy operations as the copy during argument passing can be elided in some cases, i.e. the content is just swap()ed into place

Upvotes: 4

CB Bailey
CB Bailey

Reputation: 792497

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; }

Upvotes: 15

Related Questions