The copy constructor and assignment operator

前端 未结 5 1773
攒了一身酷
攒了一身酷 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?

提交回复
热议问题