C++ Basics: Keep a Deque Reference Across End Insertions
Use the reference guarantee for deque end insertion without retaining invalid iterators.
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 deque-end-insertion-references-demo.cpp:
#include <deque>
#include <iostream>
#include <string>
int main() {
std::deque<std::string> jobs{"compile", "test"};
std::string& original_first = jobs.front();
jobs.push_front("configure");
jobs.push_back("package");
original_first += " complete";
std::cout << "Retained element: " << original_first << '\n';
std::cout << "Current front: " << jobs.front() << '\n';
std::cout << "Jobs:";
for (const auto& job : jobs) {
std::cout << " [" << job << ']';
}
std::cout << '\n';
}Compile and run it. The second command runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic deque-end-insertion-references-demo.cpp -o deque-end-insertion-references-demo &&
./deque-end-insertion-references-demoObserved output:
Retained element: compile complete
Current front: configure
Jobs: [configure] [compile complete] [test] [package]Read the result
The retained reference still names compile, although that element is no longer first. The range loop obtains new iterators after both insertions.
Apply it carefully
Insertion at either deque end preserves element references but invalidates iterators. Do not keep an old begin or end iterator for later traversal. Middle insertion has different invalidation rules; this guarantee is not a general promise that every deque mutation preserves references.
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 -- deque-end-insertion-references-demo.cpp deque-end-insertion-references-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.