为什么仅在列表初始化的情况下才会出现缩小转换警告? [英] Why does a narrowing conversion warning appear only in case of list initialization?
本文介绍了为什么仅在列表初始化的情况下才会出现缩小转换警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
class A
{
public:
A(const unsigned int val) : value(val) {}
unsigned int value;
};
int main()
{
int val = 42;
A a(val);
A b{val}; // <--- Warning in GCC, error in Microsoft Visual Studio 2015
return 0;
}
为什么仅在使用列表初始化的情况下才会出现缩小转换警告?
Why does the narrowing conversion warning appear only in case of list initialization usage?
推荐答案
列表初始化自C ++ 11开始引入,其功能禁止在内置类型之间进行隐式缩小转换.同时,另外两个使用括号和等号的旧式"(自C ++ 98起)初始化形式
list initialization was introduced since C++11 with the feature prohibiting implicit narrowing conversions among built-in types. At the same time, the other two "old-style" (since C++98) initialization forms which use parentheses and equal-sign like
int val = 42;
A a(val);
A a = val;
请勿更改其行为以符合列表初始化,因为这可能会破坏大量的旧代码库.
don't change their behavior to accord with list initialization, because that could break plenty of legacy code bases.
这篇关于为什么仅在列表初始化的情况下才会出现缩小转换警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文