The copy constructor and assignment operator

前端 未结 5 1752
攒了一身酷
攒了一身酷 2020-11-28 05:37

If I override operator= will the copy constructor automatically use the new operator? Similarly, if I define a copy constructor, will operator= aut

相关标签:
5条回答
  • 2020-11-28 06:22

    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?
    0 讨论(0)
  • 2020-11-28 06:23

    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.

    0 讨论(0)
  • 2020-11-28 06:24

    No.

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

    0 讨论(0)
  • 2020-11-28 06:27

    No, they are not the same operator.

    0 讨论(0)
  • 2020-11-28 06:33

    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.

    0 讨论(0)
提交回复
热议问题