Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 681
relaxxx Avatar asked Jan 07 '23 12:01

relaxxx


1 Answers

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.

like image 82
TemplateRex Avatar answered Jan 13 '23 15:01

TemplateRex