Explicit constructor taking multiple arguments

前端 未结 4 1080
面向向阳花
面向向阳花 2021-01-30 03:36

Does making a constructor having multiple arguments explicit have any (useful) effect?

Example:

class A {
    public:
        explicit A( in         


        
4条回答
  •  旧巷少年郎
    2021-01-30 04:08

    Up until C++11, yeah, no reason to use explicit on a multi-arg constructor.

    That changes in C++11, because of initializer lists. Basically, copy-initialization (but not direct initialization) with an initializer list requires that the constructor not be marked explicit.

    Example:

    struct Foo { Foo(int, int); };
    struct Bar { explicit Bar(int, int); };
    
    Foo f1(1, 1); // ok
    Foo f2 {1, 1}; // ok
    Foo f3 = {1, 1}; // ok
    
    Bar b1(1, 1); // ok
    Bar b2 {1, 1}; // ok
    Bar b3 = {1, 1}; // NOT OKAY
    

提交回复
热议问题