<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()는 non-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.