c++ - 隐式转换没有警告

标签 c++ casting g++ type-conversion

// g++ sizeofint.cpp --std=c++11 -Wconversion -Wall -Wextra -Werror -pedantic-errors
#include <iostream>
#include <utility>

int main(int argc, char **argv) {
    (void)argc;
    (void)argv;
    int a = 0x12345678;
    std::cout << sizeof(int) << "..." << sizeof(uint16_t) << std::endl;
    std::pair<uint16_t, uint16_t> p{a,a}; // !!!! no warning or error on conversion !!!!
    std::cout << p.first << ":" << p.second << std::endl;
    uint16_t b = a; // !!!! correct behavior: -Wconversion triggers warning, which -Werror turns to an error
    std::cout << b << std::endl;
    return 0;
}

通过上面的代码,可以清楚地看到构造p时从intuint16_t的隐式转换。然而,从 4.9.1 版开始的 g++ 在使用开头注释中提供的参数时不会提示任何转换。

后来,g++ 确实在构造 b 时提示隐式转换为 uint16_t。

我试图确保 p 的构造至少会导致警告(但最好是错误)。

有什么想法吗?是否有我不知道会触发正确行为的标志?

最佳答案

如果您的代码使用了 constexpr pair(const uint16_t& x, const uint16_t& y); std::pair<uint16_t, uint16_t> 的构造函数,您会收到警告和/或错误。你甚至不需要 -Wconversion为此 - 大括号内的缩小转换会导致程序格式错误。

但是,选择了重载解决方案 std::pairtemplate<class U, class V> constexpr pair(U&& x, V&& y);构造函数,这是一个更好的匹配。结果,转换发生了,不是在您编写的代码中,而是在该构造函数中。由于该构造函数是在系统 header 中定义的(请参阅 GCC's documentation,帽子提示 @quantdev),GCC 会抑制该警告。

虽然您可以使用 -Wsystem-headers要启用来自系统 header 的警告,该选项将产生 lots of unrelated warnings因此与 -Werror 的交互非常糟糕.

关于c++ - 隐式转换没有警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25535106/

相关文章:

c++ - boost::signal 和 std::bind 混淆,我应该尝试其他方法吗?

java - 反序列化集合时不安全的泛型转换

linux - 制作-j 8 g++ : internal compiler error: Killed (program cc1plus)

c++ - 生成运算符的签名=()?

c++ - 如何防止过度打字

c++ - 如何在 C++ 中将字符串的确切内容分配给 double

c++ - 为什么基于范围的 for 循环中二维数组的元素是 T* 而不是 T (*)[n]?

c# - 无法将 0 或 1 转换为 C# 中的 boolean 值

c++ - g++/libstdc++中std::optional的实现状态?

c++ - 在C++中获取结构的参数名称