- Qt 6.8
- Qt Core
- Obsolete Members for <QtTypeTraits>
- Qt 6.8.3 Reference Documentation

# Obsolete Members for <QtTypeTraits>

The following members of class <QtTypeTraits> are deprecated. They are provided to keep old source code working. We strongly advise against using them in new code.

## Functions

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

## Function Documentation

### `[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.

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

Note: You can make the qAsConst() function unavailable by defining the QT_NO_QASCONST macro.

### `[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 is an overloaded function.

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