Copy constructor or = operator?

前端 未结 3 946
一整个雨季
一整个雨季 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.

    0 讨论(0)
  • 2021-01-18 04:56

    g is actually created as a copy of f.

    A simple way to remember what = actually means, is just answer the question: is g already existing?

    {
       Foo g; //g construction ends here (at ';')
       g = f; // assignment (the g previous value is replaced)
    }
    
    {
       Foo g = f; //copy (same as Foo g(f): there is no "previous g" here)
    }
    
    0 讨论(0)
  • 2021-01-18 05:06
     Foo g = f; // (*)
    

    copy constructor gets invoked .Its called copy initialization of object.

    If you have not written copy constructor within class Foo then compiler generated copy constructor gets called.

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