What happens when a new object is created using another (existing) object?

巧了我就是萌 提交于 2021-02-08 09:45:13

问题


I read in a book, it says: when we initialize a newly created object using another - uses copy constructor to create a temporary object and then uses assignment operator to copy values to the new object!

And later in the book I read: When a new object is initialized using another object, compiler creates a temporary object which is copied to the new object using copy constructor. The temporary object is passed as an argument to the copy constructor.

Really confused, what actually happens!!


回答1:


I don't think either of these statements is correct - the copy-assignment operator is not called.

I would describe what happens as:

When you create a new object as a copy of an existing object, then the copy constructor is called:

// creation of new objects
Test t2(t1);
Test t3 = t1;

Only when you assign to an already existing object does the copy-assignment operator get called

// assign to already existing variable
Test t4;
t4 = t1;

We can prove this with the following little example:

#include <iostream>

class Test
{
public:
    Test() = default;
    Test(const Test &t)
    {
        std::cout << "copy constructor\n";
    }
    Test& operator= (const Test &t)
    {
        std::cout << "copy assignment operator\n";
       return *this;
    }
};

int main()
{
    Test t1;

    // both of these will only call the copy constructor
    Test t2(t1);
    Test t3 = t1;

    // only when assigning to an already existing variable is the copy-assignment operator called
    Test t4;
    t4 = t1;

    // prevent unused variable warnings
    (void)t2;
    (void)t3;
    (void)t4;

    return 0;
}

Output:

copy constructor
copy constructor
copy assignment operator

working example



来源:https://stackoverflow.com/questions/37975574/what-happens-when-a-new-object-is-created-using-another-existing-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!