簡體   English   中英

如何讓gcc警告從uint32_t到uint64_t的轉換?

[英]How to have gcc warn about conversions from uint32_t to uint64_t?

讓我們舉一個簡單的例子:

#include <vector>
#include <cstdint>

using ::std::vector;
using ::std::uint64_t;
using ::std::uint32_t;


int main(int argc, char *argv[])
{
    vector<uint64_t> v;

    uint32_t i = 1;

    v.push_back(i);

    return 0;
}

當我編譯時:

g++ -std=c++11 -Wall -Wconversion -Wpedantic a.cpp

我沒有任何轉換錯誤。 但是,我希望gcc發出警告,因為uint64_tuint32_t類型不完全匹配。 我理解uint32_t適合uint64_t ,但對我來說仍然有些代碼味道。 (我想gcc強迫我投放它)

有沒有辦法讓gcc對此發出警告?

轉換沒有問題,因為將uint32_t轉換為uint64_t不會更改值: https : //gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wconversion-499

#include <iostream>
#include <cstdint>

int main(int argc, char *argv[])
{
        std::uint32_t i = 1;
        std::uint64_t j = 1;

        // warning: conversion to 'uint32_t {aka unsigned int}' from 'uint64_t {aka long long unsigned int}' may alter its value
        // i = j;

        // No problem here
        j = i;

        // Use j to avoid an error
        std::cout << j << std::endl;

        return 0;
}

j = i;不會有編譯器標志j = i; 因為沒有問題,“氣味”只是您的偏好

uint64_t只有64位, uint32_t只有32位。 uint32更改為uint64 ,僅在高32位中加0 ,數據保持不變。 因此,編譯器不需要任何警告。 但是,當uint64_t更改為uint32_t ,編譯器會發出警告,因為可能會更改數據。 因此無法獲得您想要的警告。

您無法做到這一點,但是使用C ++ 11 UDL可以編寫自己的要使用的類集,而不是普通的整數,因此您可以提供所需的任何語義。

對於整數來說,這可能會很痛苦,我只對字符串文字使用了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM