Understanding container invariants and iterator invalidation
Within the C++ STL, there lies a crucial consideration often overlooked by many: container invariants. These invariants are, essentially, a set of conditions that always hold for a container during its lifecycle. For example, in the case of std::vector
, one such invariant might be that the elements are stored in contiguous memory locations. However, certain operations can disrupt these invariants, leading to potential pitfalls such as iterator invalidation. Armed with this knowledge, we can craft more resilient and efficient code.
Understanding iterator invalidation
A study of std::vector
is incomplete without a grasp of iterator invalidation. Iterator invalidation is akin to trying to use a bookmark after someone’s reshuffled the pages in your book. You think you’re pointing to one location, but the data there might have changed or ceased to exist.
For instance, when we push an element to a vector...