C++ Basics: Select Read-Only Access to a Mutable Object
Use as_const to pass a mutable object through a const reference without copying it.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as as-const-overload-selection-demo.cpp:
#include <iostream>
#include <string>
#include <utility>
void inspect(std::string&) { std::cout << "mutable overload\n"; }
void inspect(const std::string&) { std::cout << "const overload\n"; }
int main()
{
std::string label = "draft";
inspect(label);
inspect(std::as_const(label));
const auto& observed = std::as_const(label);
label = "ready";
std::cout << "observed: " << observed << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic as-const-overload-selection-demo.cpp -o as-const-overload-selection-demo &&
./as-const-overload-selection-demoObserved output:
mutable overload
const overload
observed: readyRead the result
The first call selects mutable access; the second selects the const-reference overload. observed sees the later assignment, showing that as_const created a reference to the original object, not a frozen snapshot.
Apply it carefully
Const access prevents ordinary mutation through that reference, but does not stop mutation through other aliases or provide synchronization between threads. Use const auto& to preserve the reference; plain auto would make a copy here. as_const intentionally rejects temporary objects to avoid this common source of dangling references.
The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- as-const-overload-selection-demo.cpp as-const-overload-selection-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.