列表初始化的缩小转换是错误还是只是警告?
Narrowing conversion of list initialization is an error or just a warning?
目前正在自学C++ primer第5版。文字说:
When used with variables of built-in type, this form of initialization has one
important property: The compiler will not let us list initialize variables of built-in type if
the initializer might lead to the loss of information:
示例代码如下:
long double ld = 3.1415926536;
int a{ld}, b = {ld}; // error: narrowing conversion required
int c(ld), d = ld; // ok: but value will be truncated
但是当我自己在 C++ 上尝试时shell:
long double a=3.14159265354;
int b(a);
int c{a};
std::cout<<a<<std::endl<<b<<std::endl<<c<<std::endl;
它只是给出了警告-Wnarrowing
但是程序成功执行了。为什么?
标准规定在程序格式错误的情况下需要诊断。当收缩转换发生在花括号初始化器中时就是这种情况。
也就是说,标准不区分错误和警告。
1.3.6 诊断消息[defns.diagnostic]
message belonging to an implementation-defined subset of the
implementation's output messages
目前正在自学C++ primer第5版。文字说:
When used with variables of built-in type, this form of initialization has one important property: The compiler will not let us list initialize variables of built-in type if the initializer might lead to the loss of information:
示例代码如下:
long double ld = 3.1415926536;
int a{ld}, b = {ld}; // error: narrowing conversion required
int c(ld), d = ld; // ok: but value will be truncated
但是当我自己在 C++ 上尝试时shell:
long double a=3.14159265354;
int b(a);
int c{a};
std::cout<<a<<std::endl<<b<<std::endl<<c<<std::endl;
它只是给出了警告-Wnarrowing
但是程序成功执行了。为什么?
标准规定在程序格式错误的情况下需要诊断。当收缩转换发生在花括号初始化器中时就是这种情况。
也就是说,标准不区分错误和警告。
1.3.6 诊断消息[defns.diagnostic]
message belonging to an implementation-defined subset of the implementation's output messages