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 cast 到const T
。
该函数是 C++17 的 std::as_const() 的 Qt 实现,与 std::move() 类似。不过,std::move() 将 lvalues 转换为 rvalues,而该函数则将非 const lvalues 转换为 const lvalues。就像 std::as_const(),它对 rvalues 无效,因为它无法在不留下悬空引用的情况下有效地实现 rvalues。
它在 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)
。这也是为什么它在设计上不支持 rvalues 的原因:返回的引用很快就会过时。因此,虽然 qAsConst( 可以工作(但会分离返回的对象):
for (QChar ch : funcReturningQString()) process(ch); // OK, the returned object is kept alive for the loop's duration
this 则不行:
for (QChar ch : qAsConst(funcReturningQString())) process(ch); // ERROR: ch is copied from deleted memory
为了防止这种构造在编译时失效,qAsConst() 有第二个被删除的重载,可以绑定到 rvalues。
注意: 您可以通过定义QT_NO_QASCONST 宏来使 qAsConst() 函数不可用。
[deprecated in 6.6]
template <typename T> void qAsConst(const T &&t)
自 6.6 版起,该函数已被弃用。我们强烈建议不要在新代码中使用该函数。
这是一个重载函数。
删除该重载函数是为了防止代码中出现悬空引用,例如
© 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.