显式构造函数和 static_cast

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;
}

可以吗,static_cast 构造 Foo 对象,即使它的构造函数被标记为 explicit

它适用于 MSVC2013 和 GCC http://ideone.com/dMS5kB

是的,static_cast 将使用 explicit 构造函数。

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 与构造函数结合意味着编译器不会执行从 intFoo 的任何隐式转换,要求一个 deliberately 强制转换它。

如果你的构造函数不是显式的,即使这个表达式 Bar('a'); 也能编译。