Is there a difference between copy initialization and direct initialization?

前端 未结 9 2681
眼角桃花
眼角桃花 2020-11-21 04:44

Suppose I have this function:

void my_test()
{
    A a1 = A_factory_func();
    A a2(A_factory_func());

    double b1 = 0.5;
    double b2(0.5);

    A c1;
         


        
9条回答
  •  暖寄归人
    2020-11-21 05:17

    Assignment is different from initialization.

    Both of the following lines do initialization. A single constructor call is done:

    A a1 = A_factory_func();  // calls copy constructor
    A a1(A_factory_func());   // calls copy constructor
    

    but it's not equivalent to:

    A a1;                     // calls default constructor
    a1 = A_factory_func();    // (assignment) calls operator =
    

    I don't have a text at the moment to prove this but it's very easy to experiment:

    #include 
    using namespace std;
    
    class A {
    public:
        A() { 
            cout << "default constructor" << endl;
        }
    
        A(const A& x) { 
            cout << "copy constructor" << endl;
        }
    
        const A& operator = (const A& x) {
            cout << "operator =" << endl;
            return *this;
        }
    };
    
    int main() {
        A a;       // default constructor
        A b(a);    // copy constructor
        A c = a;   // copy constructor
        c = b;     // operator =
        return 0;
    }
    

提交回复
热议问题