c++ - 为什么编译器不警告无符号到有符号的转换?

标签 c++ c++11 constants compiler-warnings

我最近遇到了这段代码:

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.

因此只要sconst,代码就是有效的。

关于c++ - 为什么编译器不警告无符号到有符号的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32850179/

相关文章:

linux - 使用Bash-在for循环中重复常量,返回多个结果

ruby - Ruby 类单例常量存储在哪里?

haskell - f1 = 翻转常量映射。这个功能如何运作?

c++ - 构造函数返回错误,动态内存C++

c++ - 将 char 转换为 int 时 vector 下标超出范围

c++ - 面向对象设计 - 将 C 应用程序转换为 C++

c++ - 将输出同步到 std::cout

c++ - PIMPL:导出具有单个 STL 成员的类 (std::unique_ptr)

c++ - 标准算法的并行实现和副作用

c++ - 通过其成员的地址激活嵌套 union 是否合法?