我最近遇到了这段代码:
std::size_t s = 10;
std::vector<int> v{s};
这里不是使用大小 10 进行初始化,而是使用一个元素 10
进行大小 1 的初始化。但是, vector 有一个显式构造函数,它采用 std::size_t
。随着“到处使用牙套”的大肆宣传,我想很多人都掉进了这个陷阱。如果编译器简单地警告我们正在尝试将 size_t
转换为 int
,则可以避免这种情况。
为什么编译器不需要这样做?
编辑:我的原始代码有const std::size_t s
。显然我使用的编译器都没有警告,除非我删除常量。这是错误吗?
最佳答案
不,这不是错误。参见 N3337 的 [dcl.init.list]/7:
A narrowing conversion is an implicit conversion
...
- from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type.
因此只要s
是const
,代码就是有效的。
关于c++ - 为什么编译器不警告无符号到有符号的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32850179/