简体   繁体   中英

why copy constructor is getting called even though I am actually copying to already created object in C++?

I wrote below code and I didn't understand why copy constructor is getting called.

#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 ran this program, I am getting 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 didn't understand why copy constructor is getting called when I was actually assigning the object.

If I declare abc tmp , instead of static abc tmp in myfunc() , then copy constructor is not getting called. Can any one please help me to understand what is going on here.

Because you return an object by value from myfunc , which means it's getting copied.

The reason the copy-constructor is not getting called if you don't make the object static in myfunc is because of copy elision and return value optimization (aka RVO). Note that even though your copy-constructor may not be called, it still has to exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM