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() 一样,它对右值不起作用,因为若不留下悬空引用,就无法对右值进行高效实现。
它在 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)`。这也是它被设计为对右值会失败的原因:返回的引用会过早失效。因此,虽然以下代码有效(但会使返回的对象脱离):
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。
注意:您 可以通过定义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.