C++ Basics: Transfer a Range of Unique Owners
Move iterators let a vector range insertion transfer unique_ptr elements instead of trying to copy them.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development 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 move-iterators-unique-ownership-demo.cpp:
#include <iostream>
#include <iterator>
#include <memory>
#include <vector>
int main()
{
std::vector<std::unique_ptr<int>> incoming;
incoming.push_back(std::make_unique<int>(7));
incoming.push_back(std::make_unique<int>(9));
std::vector<std::unique_ptr<int>> ready;
ready.reserve(incoming.size());
ready.insert(ready.end(), std::make_move_iterator(incoming.begin()),
std::make_move_iterator(incoming.end()));
std::cout << "ready:";
for (const auto& item : ready) {
std::cout << ' ' << *item;
}
std::cout << '\n' << "source size: " << incoming.size() << '\n';
std::cout << std::boolalpha << "source pointers empty: "
<< (!incoming[0] && !incoming[1]) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic move-iterators-unique-ownership-demo.cpp -o move-iterators-unique-ownership-demo &&
./move-iterators-unique-ownership-demoObserved output:
ready: 7 9
source size: 2
source pointers empty: trueRead the result
The destination owns the integers 7 and 9. The source vector still has two slots, but its unique_ptr elements are null after successful transfer.
Apply it carefully
Moving elements does not erase source slots. The empty-source-pointer guarantee here comes from unique_ptr; do not assume all moved-from types become empty. Move iterators adapt access, while the receiving operation performs construction or assignment. Use distinct source and destination containers, keep source iterators valid, and do not dereference transferred source pointers.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- move-iterators-unique-ownership-demo.cpp move-iterators-unique-ownership-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.