Is there a difference between copy initialization and direct initialization?

前端 未结 9 2385
眼角桃花
眼角桃花 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 04:52

    You can see its difference in explicit and implicit constructor types when you initialize an object :

    Classes :

    class A
    {
        A(int) { }      // converting constructor
        A(int, int) { } // converting constructor (C++11)
    };
    
    class B
    {
        explicit B(int) { }
        explicit B(int, int) { }
    };
    

    And in the main function :

    int main()
    {
        A a1 = 1;      // OK: copy-initialization selects A::A(int)
        A a2(2);       // OK: direct-initialization selects A::A(int)
        A a3 {4, 5};   // OK: direct-list-initialization selects A::A(int, int)
        A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int)
        A a5 = (A)1;   // OK: explicit cast performs static_cast
    
    //  B b1 = 1;      // error: copy-initialization does not consider B::B(int)
        B b2(2);       // OK: direct-initialization selects B::B(int)
        B b3 {4, 5};   // OK: direct-list-initialization selects B::B(int, int)
    //  B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int,int)
        B b5 = (B)1;   // OK: explicit cast performs static_cast
    }
    

    By default, a constructor is as implicit so you have two way to initialize it :

    A a1 = 1;        // this is copy initialization
    A a2(2);         // this is direct initialization
    

    And by defining a structure as explicit just you have one way as direct :

    B b2(2);        // this is direct initialization
    B b5 = (B)1;    // not problem if you either use of assign to initialize and cast it as static_cast
    

提交回复
热议问题