为什么初始化列表允许在 C++ 中缩小类型?

Why is the initializer list allowing type narrowing in C++?

我在 C++ 中使用 {} 初始化列表和基本类型时看到两个不同的结果。

我只是得到了警告 narrowing conversion of d from double to int inside {}

double d {3.0};
int integer {d};

但是如果我把它说得更明确一点,我就会得到一个错误 narrowing conversion of '3.0e+0' from 'double' to 'int' 里面 {}

int integer {3.0};

如果使用 {},C++11 不应该在这两种情况下阻止任何收缩转换吗?那为什么只有一种情况呢?

我将最新版本的 Eclipse 用于 C/C++ 和 MingGW。有没有可能是 C++14 无意中挡住了路?

对于 gcc 变体,您需要指定 -Werror=narrowing 以使其成为错误而不是警告。 clang 和 vc++ 更严格,默认情况下会发出错误。