Is there a difference between copy initialization and direct initialization?

前端 未结 9 2418
眼角桃花
眼角桃花 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:16

    This is from C++ Programming Language by Bjarne Stroustrup:

    An initialization with an = is considered a copy initialization. In principle, a copy of the initializer (the object we are copying from) is placed into the initialized object. However, such a copy may be optimized away (elided), and a move operation (based on move semantics) may be used if the initializer is an rvalue. Leaving out the = makes the initialization explicit. Explicit initialization is known as direct initialization.

    0 讨论(0)
  • 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 <iostream>
    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;
    }
    
    0 讨论(0)
  • 2020-11-21 05:17

    double b1 = 0.5; is implicit call of constructor.

    double b2(0.5); is explicit call.

    Look at the following code to see the difference:

    #include <iostream>
    class sss { 
    public: 
      explicit sss( int ) 
      { 
        std::cout << "int" << std::endl;
      };
      sss( double ) 
      {
        std::cout << "double" << std::endl;
      };
    };
    
    int main() 
    { 
      sss ffffd( 7 ); // calls int constructor 
      sss xxx = 7;  // calls double constructor 
      return 0;
    }
    

    If your class has no explicit constuctors than explicit and implicit calls are identical.

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