In which situations is the C++ copy constructor called?

后端 未结 7 1713
梦毁少年i
梦毁少年i 2020-12-23 02:06

I know of the following situations in c++ where the copy constructor would be invoked:

  1. when an existing object is assigned an object of it own class

7条回答
  •  忘掉有多难
    2020-12-23 02:55

    Situation (1) is incorrect and does not compile the way you've written it. It should be:

    MyClass A, B;
    A = MyClass(); /* Redefinition of `A`; perfectly legal though superfluous: I've
                      dropped the `new` to defeat compiler error.*/
    B = A; // Assignment operator called (`B` is already constructed)
    MyClass C = B; // Copy constructor called.
    

    You are correct in case (2).

    But in case (3), the copy constructor may not be called: if the compiler can detect no side effects then it can implement return value optimisation to optimise out the unnecessary deep copy. C++11 formalises this with rvalue references.

提交回复
热议问题