Copy constructor or = operator?

前端 未结 3 973
一整个雨季
一整个雨季 2021-01-18 04:40
    class Foo
    {


    };

    Foo f;
    Foo g = f; // (*)

My question is, what is being called in the line marked with (*) ? Is it the default

3条回答
  •  深忆病人
    2021-01-18 04:42

    My question is, what is being called in the line marked with (*) ? Is it the default copy ctr or '=' operator?

    The copy constructor will be called.

    Even though the = sign is being used, this is a case of initialization, where the object on the left side is constructed by supplying the expression on the right side as an argument to its constructor.

    In particular, this form of initialization is called copy-initialization. Notice, that when the type of the initializer expression is the same as the type of the initialized class object (Foo, in this case), copy-initialization is basically equivalent to direct-initialization, i.e.:

    Foo g(f); // or even Foo g{f} in C++11
    

    The subtle only difference is that if the copy constructor of Foo is marked as explicit (hard to imagine why that would be the case though), overload resolution will fail in the case of copy-initialization.

提交回复
热议问题