C++ Prog Lang书籍第139页,例如

Ick*_*ing 1 c++ type-narrowing

我正在学习Bjarne Stroustrup的"C++编程语言".在页139,它提供了以下无法编译的代码示例.

bool b2 {7}; // error : narrowing
Run Code Online (Sandbox Code Playgroud)

当我尝试这个例子时,它确实编译.有谁能解释为什么?

Kei*_*son 6

大多数编译器(不幸的是恕我直言)在默认模式下并不完全符合C++标准.

对于g ++和clang ++,您可以使用这些选项-std=c++11 -pedantic-errors来强制执行语言要求.但是,g ++的发布版本没有捕获到这个特殊的错误,这是g ++中的一个缺陷.

使用g ++ 8.2.0,声明错误地编译而没有诊断:

$ cat c.cpp
bool b2 {7};
$ g++ -std=c++11 -pedantic -c c.cpp
$
Run Code Online (Sandbox Code Playgroud)

使用clang ++ 6.0.0,错误被正确诊断:

$ clang++ -std=c++11 -pedantic -c c.cpp
c.cpp:1:10: error: constant expression evaluates to 7 which cannot be narrowed to type 'bool' [-Wc++11-narrowing]
bool b2 {7};
         ^
c.cpp:1:10: note: insert an explicit cast to silence this issue
bool b2 {7};
         ^
         static_cast<bool>( )
1 error generated.
$
Run Code Online (Sandbox Code Playgroud)

使用更新的(未发布的,源自内置的)gcc版本:

$ g++ -std=c++11 -pedantic -c c.cpp
c.cpp:1:11: error: narrowing conversion of ‘7’ from ‘int’ to ‘bool’  [-Wnarrowing]
    1 | bool b2 {7};
      |           ^
$
Run Code Online (Sandbox Code Playgroud)

clang ++已正确诊断此错误.期待g ++在版本9.0.0发布时这样做.

如果您希望在没有诊断的情况下完成转换,则可以使用其他一种初始化语法,例如:

bool b1 = 7; // sets b1 to true, no diagnostic
Run Code Online (Sandbox Code Playgroud)