简体   繁体   中英

Explicit constructor and initialization with std::initializer_list

class P { 
    public:
explicit P( int a, int b, int c) {  
    std::cout<<"calling explicit constructor"<<"\n";
    } 

};


int main() {

P z {77,5,42}; // OK

P w = {77,5,42}; // ERROR due to explicit (no implicit type conversion allowed)

}

I think {77,5,42} has the implicit type of std::initialization_list<int> . If that is the case what is not causing the failure of construction of variable z ?

I think {77,5,42} has the implicit type of std::initialization_list<int>

{77,5,42} by itself has no type. If you write auto x = {77, 5, 42} then x is of type initializer_list . Your example type P has an explicit constructor. Effectively, this means you have to write:

P w = P{77, 5, 42}

Or better:

auto w = P{77, 5, 42}

If that is the case what is not causing the failure of construction of variable z ?

The construction does not fail because you are initializing it explicitly: P x{a, b, c} does not perform an implicit conversion of any kind, but simply uses the uniform initialization syntax to invoke the (explicit) constructor of P .

The compiler is trying to do implicit conversion by finding a constructor that can match the

= {77,5,42};

part.

However, the constructor it finds, is marked explicit so it can't be used for implicit conversion. Consequently you'll get an error.

This may be of interest: What does the explicit keyword mean in C++?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM