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 good to static_castbuild an object Foo, although its constructor is marked explicit?

He works at MSVC2013 and GCC http://ideone.com/dMS5kB

+4
source share
2 answers

Yes, it static_castwill use the constructor explicit.

5.2.9 Static Casting [expr.static.cast]

4 Expression e can be explicitly converted to type T using static_cast forms , if the declaration is well-formed , for some invented temporary variable t (8.5). the effect of such an explicit transformation static_cast<T>(e)T t(e); , . e glvalue , glvalue.

+6

explicit , - int Foo, deliberately .

ctor , Bar('a'); .

+1

Source: https://habr.com/ru/post/1608446/


All Articles