C++ Basics: Distinguish a Boolean Snapshot from a Vector Proxy
Request bool explicitly when you need an independent value from vector<bool>.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and its standard-library headers, with g++ on PATH. You also need 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 vector-bool-proxy-copy-demo.cpp:
#include <iostream>
#include <vector>
int main() {
std::vector<bool> enabled{false, true};
auto first_proxy = enabled[0];
const bool first_snapshot = enabled[0];
first_proxy = true;
std::cout << std::boolalpha;
std::cout << "Stored flag: " << enabled[0] << '\n';
std::cout << "Snapshot: " << first_snapshot << '\n';
enabled[0] = false;
std::cout << "Proxy after element change: "
<< static_cast<bool>(first_proxy) << '\n';
}Compile and run it. The second command runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic vector-bool-proxy-copy-demo.cpp -o vector-bool-proxy-copy-demo &&
./vector-bool-proxy-copy-demoObserved output:
Stored flag: true
Snapshot: false
Proxy after element change: falseRead the result
The auto variable holds a proxy linked to the stored bit, not an independent boolean. The explicitly typed bool keeps its original false value.
Apply it carefully
A vector<bool> element access can produce a proxy rather than bool&. Do not retain proxies across operations that invalidate their underlying storage or after container destruction. This example never resizes the vector. Use an explicit bool for a snapshot, and do not assume this specialization provides ordinary contiguous bool objects.
The C++ working draft documents the relevant container rules. This example uses only features available in C++20, even though the linked draft also includes newer additions.
Clean up
Remove only the source and executable created here, then remove the empty practice directory:
rm -- vector-bool-proxy-copy-demo.cpp vector-bool-proxy-copy-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.