Qt::totally_ordered_wrapper Class
template <typename P> class Qt::totally_ordered_wrapperQt::totally_ordered_wrapper 是一种封装类型,为封装类型提供严格的总顺序。更多
头文件: | #include <QtCompare> |
CMake: | find_package(Qt6 REQUIRED COMPONENTS Core) target_link_libraries(mytarget PRIVATE Qt6::Core) |
qmake: | QT += core |
自 | Qt 6.8 |
详细说明
它的主要用途之一是在比较指针时防止未定义行为(UB)。
请看下面这个简单的类:
template <typename T> struct PointerWrapperBad { int val; T *ptr; };
对PointerWrapperBad
类型的两个实例进行词典比较会导致 UB,因为它会在ptr
成员上调用operator<()
或operator<=>()
。
要解决这个问题,可以使用新的封装类型:
template <typename T> struct PointerWrapperGood { int val; Qt::totally_ordered_wrapper<T *> ptr; friend bool operator==(PointerWrapperGood lhs, PointerWrapperGood rhs) noexcept = default; friend auto operator<=>(PointerWrapperGood lhs, PointerWrapperGood rhs) noexecpt = default; };
Qt::totally_ordered_wrapper
类型的operator<()
运算符和operator<=>()
运算符(如果可用)分别使用std::less和std::compare_three_way函数对象,在进行比较时提供严格的指针总顺序。
因此,PointerWrapperGood::ptr
成员的关系运算符将得到很好的定义,我们甚至可以=default
PointerWrapperGood
类的关系运算符,如上图所示。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.