Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling assignment operator in copy constructor

Are there some drawbacks of such implementation of copy-constructor?

Foo::Foo(const Foo& i_foo) {    *this = i_foo; } 

As I remember, it was recommend in some book to call copy constructor from assignment operator and use well-known swap trick, but I don't remember, why...

like image 758
stas Avatar asked Apr 14 '10 16:04

stas


People also ask

What does copy assignment operator do in C++?

A trivial copy assignment operator makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially copy-assignable.

What is the difference between copy constructor and copy assignment operator?

Copy constructor is a special constructor for creating a new object as a copy of an existing object. In contrast, assignment operator is an operator that is used to assign a new value to a variable.

Can I call constructor from copy constructor?

The answer is No. The creation of the object memory is done via the new instruction. Copy constructor is then in charge of the actual copying (relevant only when it's not a shallow copy, obviously). You can, if you want, explicitly call a different constructor prior to the copy constructor execution.


2 Answers

Yes, that's a bad idea. All member variables of user-defined types will be initialized first, and then immediately overwritten.

That swap trick is this:

Foo& operator=(Foo rhs) // note the copying {    rhs.swap(*this); //swap our internals with the copy of rhs    return *this; } // rhs, now containing our old internals, will be deleted  
like image 186
sbi Avatar answered Oct 04 '22 11:10

sbi


There are both potential drawbacks and potential gains from calling operator=() in your constructor.

Drawbacks:

  • Your constructor will initialize all the member variables whether you specify values or not, and then operator= will initialize them again. This increases execution complexity. You will need to make smart decisions about when this will create unacceptable behavior in your code.

  • Your constructor and operator= become tightly coupled. Everything you need to do when instantiating your object will also be done when copying your object. Again, you have to be smart about determining if this is a problem.

Gains:

  • The codebase becomes less complex and easier to maintain. Once again, be smart about evaluating this gain. If you have a struct with 2 string members, it's probably not worth it. On the other hand if you have a class with 50 data members (you probably shouldn't but that's a story for another post) or data members that have a complex relationship to one another, there could be a lot of benefit by having just one init function instead of two or more.
like image 30
John Dibling Avatar answered Oct 04 '22 13:10

John Dibling