Search code examples
c++copy-constructorassignment-operator

Are there drawbacks to calling the assignment operator in the 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...


Solution

  • 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