加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 隐式转换没有警告

发布时间:2020-12-16 09:53:57 所属栏目:百科 来源:网络整理
导读:// g++ sizeofint.cpp --std=c++11 -Wconversion -Wall -Wextra -Werror -pedantic-errors#include iostream#include utilityint main(int argc,char **argv) { (void)argc; (void)argv; int a = 0x12345678; std::cout sizeof(int) "..." sizeof(uint16_t)
// 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时从int到uint16_t的隐式转换.但是,从版本4.9.1开始,当使用注释中提供的参数时,g不会抱怨任何转换.

后来,g确实抱怨在构造b时隐式转换为uint16_t.

我正在努力确保p的结构至少会产生警告(但最好是错误).

有什么想法吗?是否有一个我不知道要触发正确行为的旗帜?

解决方法

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

但相反,重载决策选择了std :: pair的模板< class U,class V> constexpr对(U& x,V& y);构造函数,这是一个更好的匹配.因此,转换发生在您编写的代码中,而不是在构造函数内部.由于该构造函数是在系统头中定义的(参见GCC’s documentation,帽子提示@quantdev),因此GCC会禁止该警告.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读