views:

219

answers:

3

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...

+2  A: 

You're looking for Scott Meyers' Effective C++ Item 12: Copy all parts of an object.

Billy ONeal
+7  A: 

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=(const Foo& rhs)
{
   Foo tmp(rhs); // use copy ctor
   tmps.swap(*this); //swap our internals with the copy of rhs
   return *this;
} // tmp, now containing our old internals, will be deleted 
sbi
"that's a bad idea," is too broad a statement IMO. By saying this, you are potentially micro-optimizing prematurely. If you write assignment code in both the ctor and `op=()`, you create a duplication of code and violate DRY. Figure out if the costs involved in double-initialization, compare them to the benefits gained by reducing the complexity in the code base, and then decide which way is right.
John Dibling
The nice thing about the swap trick is that it deals automatically with self-assignment, and (assuming `.swap()` doesn't throw) is strongly exception-safe, in that either the assignment succeeds or it's left unchanged and an exception is thrown.
David Thornley
Except these days, the trick is done better by passing rhs by value. See http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
Kaz Dragon
@Kaz: You're right. `<sigh>` That's twice these days that I had to admit that I'm doing something mainly out of old habit, not why it is (still) considered state of the art. Maybe I'm getting to old.
sbi
+1  A: 

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.
John Dibling