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() を使用してください。
t をconst T にキャストした値を返します。
この関数は、C++17 の std::as_const() の Qt 実装であり、std::move() と同様のキャスト関数です。しかし、std::move() が lvalue を rvalue に変換するのに対し、この関数は非 const の lvalue を const の lvalue に変換します。 std::as_const() と同様に、rvalue に対しては機能しません。これは、dangling reference を残さずに 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);もちろん、このケースでは、最初からs をconst として宣言することも可能であり(おそらくそうすべきでしょう):
しかし、多くの場合、そうすることは容易ではありません。
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() には、rvalue にバインドする 2 つ目の(削除済みの)オーバーロードが用意されています。
注: QT_NO_QASCONST マクロを定義することで、qAsConst() 関数を使用できないようにすることができます 。
[delete, 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これはオーバーロードされた関数です。
© 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.