Implicit Conversion Warning

// 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;
}

      

With the above code, you can clearly see the implicit conversion from int

to uint16_t

when building p

. However, g ++ since 4.9.1 does not complain about any conversions when using the parameters presented in the comment at the beginning.

Later, g ++ complains about implicit conversion to uint16_t at build b

.

I am trying to make sure that the construct p

will produce at least a warning (but preferably an error).

Any thoughts? Is there a flag that I am not aware of to trigger the correct behavior?

+3


source to share


1 answer


If your code used a constructor constexpr pair(const uint16_t& x, const uint16_t& y);

std::pair<uint16_t, uint16_t>

, you will get a warning and / or an error. You don't even need -Wconversion

to do this - narrowing conversions inside curly braces makes the program ill-formed.

But instead, the overload resolution is chosen by std::pair

template<class U, class V> constexpr pair(U&& x, V&& y);

constructor, which better matches. As a result, the conversion does not take place inside the code you wrote, but inside this constructor. Because this constructor is defined in the system header (see the GCC documentation , tip tip @quantdev), the warning is suppressed by GCC.



While you can use it -Wsystem-headers

to include warnings from system headers, this setting will produce many unrelated warnings and therefore interacts very strongly with -Werror

.

+7


source







All Articles