Is there a difference between copy initialization and direct initialization?

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

    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 
    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.

提交回复
热议问题