Can I call a copy constructor explicitly?

前端 未结 6 1583
名媛妹妹
名媛妹妹 2021-02-02 12:50

I\'m a little confused as to the mechanics of the copy constructor. Correct me if I\'m wrong:

If a method takes a reference to an object as a parameter, and the class d

6条回答
  •  半阙折子戏
    2021-02-02 13:23

    No, if a function take a reference:

    void f1( Object & o );   // call by reference
    

    then no copy is made. If a function takes a value:

    void f2( Object o );   // call by value
    

    then a copy is created by the compiler using the copy constructor.

    And yes, when you say:

    Object * obj = new Object(anotherObject);   // not &anotherObject
    

    the copy constructor is used explicitly (assuming anotherObject is of type Object.) There is nothing magic about the use of new here, however - in this case:

    Object obj2(anotherObject);
    

    the copy constructor is also used.

提交回复
热议问题