Linked Lists using std::forward_list

Iterator Invalidation in std::forward_list

When do iterators become invalidated in a std::forward_list?

Abstract art representing computer programming

Iterators in a std::forward_list can become invalidated under certain circumstances:

Modifying Operations

Any operation that modifies the list, such as insert_after(), emplace_after(), erase_after(), push_front(), emplace_front(), pop_front(), or clear(), invalidates iterators pointing to the elements following the modified element.

#include <forward_list>
#include <iostream>

int main() {
  std::forward_list<int> list{1, 2, 3, 4};
  auto it = list.begin();
  ++it;                      // points to 2
  list.insert_after(it, 5);  // 'it' invalidated
  std::cout << *it;          // undefined behavior
}

Reallocation

If the internal memory of the forward_list is reallocated (e.g., due to a call to resize()), all iterators are invalidated.

To avoid issues, it's best to re-obtain iterators after performing any modifying operation on the forward_list.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved