Hidden narrowing conversion from int to uint8_t

Consider the following code snippet:

#include <cstdint>

class A
{
public:

    explicit A(uint8_t p_a){ m_a = p_a; };
    uint8_t get_a() const {return m_a;}

private:

    uint8_t m_a;
};

int main()
{
    A a {0x21U};
    A aa{0x55U};

    uint8_t mask{a.get_a() | aa.get_a()};

    return 0;
}

When I try to compile this ( gcc 5.4.0), I get the following error:

main.cpp: In functionint main()’:
main.cpp:20:28: warning: narrowing conversion of(int)(a.A::get_a() | aa.A::get_a())frominttouint8_t {aka unsigned char}’ inside { } [-Wnarrowing]
     uint8_t mask{a.get_a() | aa.get_a()};

I don’t understand why it narrows at all. The type is intnever used anywhere in my code, everything is written in terms of unsigned chars. Even if I explicitly pass unsigned char, I get an error:

uint8_t mask{static_cast<uint8_t>(a.get_a()) | static_cast<uint8_t>(aa.get_a())};

In fact, to solve this problem, I need to remove {}-initialization. Then it works:

uint8_t mask = a.get_a() | aa.get_a();

Why is this necessary?

+4
source share
4 answers

You were close with this:

uint8_t mask{static_cast<uint8_t>(a.get_a()) | static_cast<uint8_t>(aa.get_a())};

But a.get_a(), and aa.get_a()already uint8_t, so the actor does not do anything.

This is an operation |that:

  • int ( , - )
  • int

, :

uint8_t mask{static_cast<uint8_t>(a.get_a() | aa.get_a())};

, {} -, , , . .

uint8_t mask = a.get_a() | aa.get_a();

, .

+5

, | , , int unsigned int .

++ 17 [expr], 11:

, , . , , . , :

  • - ,...

  • long double,...

  • , double,...

  • , float,...

  • . :...

- get_a() uint8_t int. , | int, uint8_t .

+2

:

prvalues ​​ (, char) prvalues ​​ (, int).

a.get_a() | aa.get_a() - prvalue

+1

, .

uint8_t mask{a.get_a() | aa.get_a()};

auto i = a.get_a() | aa.get_a(); // i is int

int, int uint8_t, :

If the initializer clause is an expression, implicit conversions are allowed according to copy initialization, unless they are narrowed (as in list initialization) (starting with C ++ 11).

+1
source

Source: https://habr.com/ru/post/1695004/


All Articles