Skip to content
C++ Basics: Move a List Task Without Invalidating Its Iterator

C++ Basics: Move a List Task Without Invalidating Its Iterator

November 8, 2026

Move a task between lists with splice while keeping an iterator to the same element.

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 1

Run the example

Save this as list-splice-task-transfer-demo.cpp:

#include <iostream>
#include <iterator>
#include <list>
#include <string>

int main()
{
    std::list<std::string> pending{"download", "verify", "publish"};
    std::list<std::string> active;
    auto task = std::next(pending.begin());
    active.splice(active.end(), pending, task);
    *task += " checksums";
    std::cout << "pending:";
    for (const auto& name : pending) std::cout << ' ' << name;
    std::cout << "\nactive: " << active.front() << '\n';
    std::cout << "same element: " << std::boolalpha
              << (task == active.begin()) << '\n';
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic list-splice-task-transfer-demo.cpp -o list-splice-task-transfer-demo &&
./list-splice-task-transfer-demo

Observed output:

pending: download publish
active: verify checksums
same element: true

Read the result

The middle task leaves pending and becomes the first active task. Updating it through the saved iterator updates active. The final comparison confirms that the iterator now identifies the transferred element in the destination list.

Apply it carefully

The single-element splice overload transfers a node without copying or moving its value. The source iterator must identify an element, not end(). Both lists must have equal allocators; the default allocators here satisfy that requirement. After transfer, use the iterator with the destination list. List iterators are not random-access iterators.

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 -- list-splice-task-transfer-demo.cpp list-splice-task-transfer-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on