The copy constructor and assignment operator

*爱你&永不变心* 提交于 2019-11-26 19:51:02
sgokhales

No, they are different operators.

The copy constructor is for creating a new object. It copies a existing object to a newly constructed object.The copy constructor is used to initialize a new instance from an old instance. It is not necessarily called when passing variables by value into functions or as return values out of functions.

The assignment operator is to deal with an already existing object. The assignment operator is used to change an existing instance to have the same values as the rvalue, which means that the instance has to be destroyed and re-initialized if it has internal dynamic memory.

Useful link :

No. Unless you define a copy ctor, a default will be generated (if needed). Unless you define an operator=, a default will be generated (if needed). They do not use each other, and you can change them independently.

No. They are different objects.

If your concern is code duplication between copy constructor and assignment operator, consider the following idiom, named copy and swap :

struct MyClass
{
    MyClass(const MyClass&); // Implement copy logic here
    void swap(MyClass&) throw(); // Implement a lightweight swap here (eg. swap pointers)

    MyClass& operator=(MyClass x)
    {
        x.swap(*this);
        return *this;
    }
};

This way, the operator= will use the copy constructor to build a new object, which will get exchanged with *this and released (with the old this inside) at function exit.

No, they are not the same operator.

stijn

No.

And definitely have a look at the rule of three (or rule of five when taking rvalues into account)

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