<QtTypeTraits> - Qt Type Traits
用于类型特征和转换的功能。更多
Header: | #include <QtTypeTraits> |
Since: | Qt 6.5 |
函数
T | qExchange(T &obj, U &&newValue) |
(since 6.2) std::underlying_type_t<Enum> | qToUnderlying(Enum e) |
宏
(since 6.8) | QT_NO_QASCONST |
(since 6.6) | QT_NO_QEXCHANGE |
函数文档
[constexpr noexcept(...)]
template <typename T, typename U = T> T qExchange(T &obj, U &&newValue)
用newValue 替换obj 的值,并返回obj 的旧值。
这是 Qt 对 std::exchange() 的实现。它与 std::exchange() 的区别仅在于,它在 C++20 之前就已经是constexpr
,在 C++23 之前就已经是 noexcept。
我们强烈建议在不需要 C++20 或 C++23 变体时使用 std::exchange()。你可以通过定义QT_NO_QEXCHANGE 宏来使 qExchange() 不可用。
下面介绍如何使用 qExchange() 实现移动构造函数:
MyClass(MyClass &&other) : m_pointer{qExchange(other.m_pointer, nullptr)}, m_int{qExchange(other.m_int, 0)}, m_vector{std::move(other.m_vector)}, ...
对于类类型的成员,我们可以使用 std::move(),因为它们的移动构造函数会做正确的事情。但对于标量类型(如原始指针或整数类型),move 与 copy 相同,尤其是对于指针,这并不是我们所期望的。因此,我们不能对这类类型使用 std::move(),但我们可以使用 std::exchange()/qExchange() 来确保在初始化下一个数据成员时,源对象的成员已经重置,这在构造函数出现异常时可能会派上用场。
下面是如何使用 qExchange() 编写一个循环,消耗它所遍历的集合:
for (auto &e : qExchange(collection, {}) doSomethingWith(e);
这等同于下面的代码,但要啰嗦得多:
{ auto tmp = std::move(collection); collection = {}; // or collection.clear() for (auto &e : tmp) doSomethingWith(e); } // destroys 'tmp'
这是绝对安全的,因为只要循环运行,for-loop 就会一直保留 qExchange() 的结果,从而保存了临时变量的声明。但要注意的是,qExchange() 返回的是非const 对象,因此 Qt 容器可能会脱离。
注意: 当std::conjunction_v<std::is_nothrow_move_constructible<T>,
std::is_nothrow_assignable<T &, U>>
为true
时,此函数为 noexcept。
[constexpr noexcept, since 6.2]
template <typename Enum> std::underlying_type_t<Enum> qToUnderlying(Enum e)
将枚举器e 转换为以其枚举底层类型表示的等效值。
此函数在 Qt 6.2 中引入。
© 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.