以下成员源于类 <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
)
This function is deprecated since 6.6. We strongly advise against using it in new code.
Use std::as_const() instead.
返回
t
cast to
const T
.
This function is a Qt implementation of C++17's std::as_const(), a cast function like std::move(). But while std::move() turns lvalues into rvalues, this function turns non-const lvalues into const lvalues. Like std::as_const(), it doesn't work on rvalues, because it cannot be efficiently implemented for rvalues without leaving dangling references.
Its main use in Qt is to prevent implicitly-shared Qt containers from detaching:
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);
Of course, in this case, you could (and probably should) have declared
s
as
const
in the first place:
const QString s = ...; for (QChar ch : s) // ok, no detach attempt on const objects process(ch);
but often that is not easily possible.
It is important to note that qAsConst() does not copy its argument, it just performs a
const_cast<const T&>(t)
. This is also the reason why it is designed to fail for rvalues: The returned reference would go stale too soon. So while this works (but detaches the returned object):
for (QChar ch : funcReturningQString()) process(ch); // OK, the returned object is kept alive for the loop's duration
this would not:
for (QChar ch : qAsConst(funcReturningQString())) process(ch); // ERROR: ch is copied from deleted memory
To prevent this construct from compiling (and failing at runtime), qAsConst() has a second, deleted, overload which binds to rvalues.
[deprecated in 6.6]
template <typename T>
void
qAsConst
(const
T
&&
t
)
This function is deprecated since 6.6. We strongly advise against using it in new code.
这是重载函数。
This overload is deleted to prevent a dangling reference in code like
for (QChar ch : qAsConst(funcReturningQString())) process(ch); // ERROR: ch is copied from deleted memory