The copy constructor and assignment operator

…衆ロ難τιáo~ 提交于 2019-11-26 07:28:12

问题


If I override operator= will the copy constructor automatically use the new operator? Similarly, if I define a copy constructor, will operator= automatically \'inherit\' the behavior from the copy constructor?


回答1:


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 :

  • Copy Constructors, Assignment Operators, and More
  • Copy constructor and = operator overload in C++: is a common function possible?



回答2:


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.




回答3:


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.




回答4:


No, they are not the same operator.




回答5:


No.

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



来源:https://stackoverflow.com/questions/5368258/the-copy-constructor-and-assignment-operator

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