Obsolete Members for <QtTypeTraits>

クラス<QtTypeTraits> の以下のメンバーは非推奨です。これらは古いソース・コードの動作を維持するために提供されています。新しいコードでは使用しないことを強くお勧めします。

関数

(deprecated in 6.6) typename std::add_const<T>::type &qAsConst(T &t)
(deprecated in 6.6) void qAsConst(const T &&t)

関数のドキュメント

[constexpr noexcept, deprecated in 6.6] template <typename T> typename std::add_const<T>::type &qAsConst(T &t)

この関数は6.6から非推奨となった。新しいコードでは使わないことを強く勧める。

代わりに std::as_const() を使ってください。

tconst T にキャストして返します。

この関数はC++17のstd::as_const()をQtで実装したもので、std::move()のようなキャスト関数です。しかし、std::move() が lvalue を rvalue に変換するのに対し、この関数は非 const lvalue を const lvalue に変換します。std::as_const()と同様、rvalueでは動作しません。なぜなら、rvalueでは参照をぶら下げずに効率的に実装できないからです。

Qt での主な用途は、暗黙的に共有されている Qt コンテナがデタッチされるのを防ぐことです:

    QString s = ...;
    for (QChar ch : s) // detaches 's' (performs a deep-copy if 's' was shared)
        process(ch);
    for (QChar ch : qAsConst(s)) // ok, no detach attempt
        process(ch);

もちろん、この場合、sconst として最初に宣言することもできます(おそらくそうすべきです):

    const QString s = ...;
    for (QChar ch : s) // ok, no detach attempt on const objects
        process(ch);

しかし、多くの場合、それは簡単にはできません。

qAsConst()は引数をコピーするのではなく、単にconst_cast<const T&>(t) 。これはrvalueに対して失敗するように設計されている理由でもあります:返された参照はすぐに古くなってしまうからである。返された参照はすぐに古くなってしまうからです:

    for (QChar ch : funcReturningQString())
        process(ch); // OK, the returned object is kept alive for the loop's duration

これはうまくいきません:

    for (QChar ch : qAsConst(funcReturningQString()))
        process(ch); // ERROR: ch is copied from deleted memory

この構文がコンパイルされないように(そして実行時に失敗しないように)、qAsConst()にはrvaluesにバインドする2つ目の削除されたオーバーロードがあります。

注意: QT_NO_QASCONST マクロを定義することで、qAsConst() 関数を使用できなくすることができます。

[deprecated in 6.6] template <typename T> void qAsConst(const T &&t)

この関数は6.6から非推奨となった。新しいコードでは使用しないことを強くお勧めします。

これはオーバーロードされた関数です。

このオーバーロードは、以下のようなコードでダングリング参照を防ぐために削除されました。

    for (QChar ch : qAsConst(funcReturningQString()))
        process(ch); // ERROR: ch is copied from deleted memory

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