<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)

将obj 的值替换为newValue ,并返回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(),因为它们的移动构造函数会正确处理。但对于标量类型(如原始指针或整数类型),移动操作等同于复制操作,这尤其对于指针而言,并非我们所期望的结果。 因此,我们不能对这类类型使用 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 循环在运行期间会一直保留 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 中引入。

宏文档

[since 6.8] QT_NO_QASCONST

定义此宏将导致 qAsConst() 函数不可用。

该宏在 Qt 6.8 中引入。

另请参阅 qAsConst 。

[since 6.6] QT_NO_QEXCHANGE

定义此宏将导致无法使用qExchange()函数。

该宏在 Qt 6.6 中引入。

另请参阅 qExchange 。

© 2026 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.