Is it an assigment or a copy construct?

Suppose we have the following code:

myclass a;
myclass b = a;

Does the  second line invoke b’s default constructor and then the assignment operator?  Wouldn’t it be more efficient to rewrite it like this:

myclass b(a);

Actually, though, the first and second versions are equivalent: both result in a single copy constructor call; neither one uses the assignment operator.

Let’s try an example to demonstrate this.

#include <iostream>

class myclass
{
private:
    std::string innards;
public:
    myclass& operator=(const myclass& c);
    myclass(const myclass& c);
    myclass();
    ~myclass();
};

myclass& myclass::operator=(const myclass& c)
{
    std::cout << "myclass::operator=\n";
    if(&c != this)
    {
        innards = c.innards;
    }
    return *this;
}

myclass::myclass(const myclass& c)
 : innards(c.innards)
{
    std::cout << "myclass::myclass(const myclass& c)\n";
}

myclass::myclass()
{
    std::cout << "myclass::myclass()\n";
}

myclass::~myclass()
{
    std::cout << "myclass::~myclass()\n";
}

int main(void)
{
    myclass a;
    myclass b = a;
    return 0;
}

The output is:

myclass::myclass()
myclass::myclass(const myclass& c)
myclass::~myclass()
myclass::~myclass()

A default construct, a copy construct, and two destructs.

Advertisements

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s