CKTIS / C++
std::as_const: a const view of an lvalue
std::as_const returns const T& to an existing lvalue without copying. Its rvalue overload is deleted to prevent a dangling reference.
Version: C++23
Syntax
template<class T>
constexpr std::add_const_t<T>& as_const(T& value) noexcept;
template<class T>
void as_const(const T&&) = delete;std::as_const from <utility> preserves object identity while exposing it through a const reference. It can explicitly select a read-only overload or prevent accidental mutation in one section of code. The referred-to object type is const-qualified; the reference itself is not cv-qualified.
The function makes no copy and does not extend lifetime. Changes made through another non-const alias remain visible through the returned reference. Calling it with a temporary is a compile-time error.
A const reference does not make the object globally immutable or thread-safe. Const member functions may change mutable state, and concurrent writes through another alias still require synchronization.
Examples
#include <iostream>
#include <type_traits>
#include <utility>
int main() {
int value = 7;
const auto& view = std::as_const(value);
std::cout << view << ' '
<< std::is_const_v<std::remove_reference_t<decltype(view)>> << '\n';
}
Result
7 1
std::as_const → 7 1