Any difference between copy-list-initialization and traditional copy-initialization?

前端 未结 2 862
长情又很酷
长情又很酷 2021-02-02 01:06

Except for supporting multiple arguments, disallowing narrowing conversion, matching constructor taking std::initializer_list argument, what else is different for copy-list-init

2条回答
  •  孤独总比滥情好
    2021-02-02 01:48

    Copy-initialization always considers availability of copy constructors, while copy-list-initialization doesn't.

    class B {};
    struct A 
    {
      A(B const&) {}
      A(A const&) = delete;
    };
    
    B b;
    A a1 = {b};  // this compiles
    A a2 = b;    // this doesn't because of deleted copy-ctor
    

    This is because copy-list-initialization is identical to direct-list-initialization except in one situation - had A(B const&) been explicit, the former would've failed, while the latter will work.

    class B {};
    struct A 
    {
      explicit A(B const&) {}
    };
    
    
    int main()
    {
        B b;
        A a1{b};    // compiles
        A a2 = {b}; // doesn't compile because ctor is explicit
    }
    

提交回复
热议问题