[Development] QPair vs std::pair difference with narrowing conversion

Giuseppe D'Angelo dangelog at gmail.com
Sat Jun 3 15:08:35 CEST 2023


Il sab 3 giu 2023, 14:37 Elvis Stansvik <elvstone at gmail.com> ha scritto:

> Hi all,
>
> I was going through some legacy code and came across a behavioral
> difference between QPair and std::pair:
>
> estan at edison:~$ cat test.cpp
> #include <QPair>
> #include <utility>
>
> int main(void) {
>    int i = 1;
>    QPair<unsigned, unsigned>{i, i};
>    std::pair<unsigned, unsigned>{i, i};
>    return 0;
> }
> estan at edison:~$ g++ -isystem /usr/include/x86_64-linux-gnu/qt5
> -isystem /usr/include/x86_64-linux-gnu/qt5/QtCore -Wall -fPIC -c
> test.cpp
> test.cpp: In function ‘int main()’:
> test.cpp:6:31: warning: narrowing conversion of ‘i’ from ‘int’ to
> ‘unsigned int’ [-Wnarrowing]
>    6 |     QPair<unsigned, unsigned>{i, i};
>      |                               ^
> test.cpp:6:34: warning: narrowing conversion of ‘i’ from ‘int’ to
> ‘unsigned int’ [-Wnarrowing]
>    6 |     QPair<unsigned, unsigned>{i, i};
>      |                                  ^
> estan at edison:~$
>
> Just curious if anyone know why what difference between QPair and
> std::pair makes the narrowing conversion warning pop up in the QPair
> case and not the std::pair case?
>

Because QPair is lacking constructor 3
https://en.cppreference.com/w/cpp/utility/pair/pair

https://codebrowser.dev/qt5/qtbase/src/corelib/tools/qpair.h.html

That constructor hides the narrowing into std::pair's code.



> Note the warning only appears when using aggregate initialization with { }.
>

It's list initialization, but it's not aggregate initialization, neither
class is an aggregate as they have user defined constructors.



> Using GCC 11.3.0 and Qt 5.15.3.
>


Note: I made QPair an alias to std::pair in Qt 6.

Hth,


> Cheers,
> Elvis
> --
> Development mailing list
> Development at qt-project.org
> https://lists.qt-project.org/listinfo/development
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20230603/d944ea02/attachment.htm>


More information about the Development mailing list