C ++大括号分隔初始化列表

时间:2013-09-04 20:31:47

标签: c++ initialization curly-braces

我正在阅读Stroustrup最新的C ++书籍(第4版),本书中的以下示例不会引发错误。

#include <iostream>
using namespace std;

int main(const int argc, const char* argv[]) {

  // Narrowing conversion.
  // According to Stroustrup, an error should happen here
  // because the curly-brace-delimited initializer 
  // saves us from conversions that lose information.
  // But after compiling and running the code the output is 7.
  int i2 {7.2};
  cout << i2 << endl;

  return 0;
}

我正在使用以下命令在Gentoo系统上编译代码。 (g ++版本:4.6.3)

g++ -std=c++0x -o output input.cpp

为什么不抛出错误?

1 个答案:

答案 0 :(得分:3)

更新版本的gcc(4.8.1),将其视为警告:

trash9.cpp: In function 'int main(int, const char**)':
trash9.cpp:11:14: warning: narrowing conversion of '7.2000000000000002e+0' from
'double' to 'int' inside { } [-Wnarrowing]
   int i2 {7.2};

标准要求编译器发出“诊断”,因此(使用正确的文档)这无疑是合格的。编译器随后可以继续编译代码。

VC ++更接近你想要的东西:

trash9.cpp(11) : error C2397: conversion from 'double' to 'int' requires a narro
wing conversion
相关问题