Why is the copy constructor invoked even though I actually copy the already created object in C ++?

I wrote the code below, and I did not understand why it calls the copy constructor.

#include <iostream>

using namespace std;

class abc
{
    public:
        abc()
        {
            cout << "in Construcutor" << (this) << endl;
        };

        ~abc()
        {
            cout << "in Destrucutor" << (this) << endl;
        };

        abc(const abc &obj)
        {
            cout << "in copy constructor" << (this) << endl;
            cout << "in copy constructor src " << &obj << endl;
        }

        abc& operator=(const abc &obj)
        {
            cout << "in operator =" << (this) << endl;
            cout << "in operator = src " << &obj << endl;
        }
};

abc myfunc()
{
    static abc tmp;

    return tmp;
}

int main()
{
    abc obj1;

    obj1 = myfunc();

    cout << "OK. I got here" << endl;
}

when i run this program i get the following output

in Construcutor0xbff0e6fe
in Construcutor0x804a100
in copy constructor0xbff0e6ff
in copy constructor src 0x804a100
in operator =0xbff0e6fe
in operator = src 0xbff0e6ff
in Destrucutor0xbff0e6ff
OK. I got here
in Destrucutor0xbff0e6fe
in Destrucutor0x804a100

I did not understand why the copy constructor is called when I actually assigned the object.

If I declare abc tmpinstead of static abc tmpin myfunc(), then the copy constructor will not be called. Can someone help me understand what is going on here.

+4
source share
1 answer

Because you are returning an object by value from myfunc, which means that it is copied.

, - , static myfunc - copy elision (aka RVO). , - , .

+11

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


All Articles