简体   繁体   中英

Explicit constructor and static_cast

struct Foo
{
    explicit Foo(int a):m(a){}
    int padd1, m, padd2;
};

void Bar(Foo){}

int main()
{
    Bar(11); // OK, gives error
    auto x = static_cast<Foo>(37);
    x.m;
}

Is it ok, that static_cast construct Foo object even though its constructor is marked explicit ?

It works in MSVC2013 and GCC http://ideone.com/dMS5kB

Yes, static_cast will use the explicit constructor.

5.2.9 Static cast [expr.static.cast]

4 An expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed , for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The expression e is used as a glvalue if and only if the initialization uses it as a glvalue.

explicit combined with constructor means that compiler won't perform any implicit conversion from int to Foo , asking one to deliberately cast it.

If your ctor wasn't explicit , even this expression Bar('a'); would compile.

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