Why is there a copy before the appointment?

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(ai){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 result:

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

It seems that "o2 = o1" made a copy first, and then the task, and I wonder what kind of story. Thanks!

+6
source share
2 answers

Since you are passing the value to your assignment operator:

 void operator=(const A a) 

You should probably have followed the link, and you should also return a link to the assigned object:

 A& operator=(const A& a) { std::cout << "A assign" << std::endl; return *this; } 
+15
source

It seems you have configured the assignment operator correctly:

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

The argument is passed in as a copy to the binding operator, and the compiler really needs to make that copy in your setup. If you went through a temporary copy, you could avoid:

 o2 = A(); 

Thus, the implementation above actually has several interesting properties:

  • it uses the functions already written: the copy constructor is either generated or written, but does the right thing, and if you want to have a job, you probably want to have a swap() member as well
  • assignment is a strong exception if the swap() operation is not thrown, as it should be. When dispensers enter an image, everything should be done a little differently, although
  • assignment tries to avoid the actual copy operations, since the copy may be deleted in some cases during the transfer of the argument, i.e. the contents are just swap() ed in place
+4
source

Source: https://habr.com/ru/post/911304/


All Articles