Can anyone provide me with case where std::deque needs reallocation as
a consequence of some operations performed on it.
In a typical scenario, never. While the precise implementation details of a deque
are unspecified, to preserve the iterator/pointer/reference invalidation* and algorithmic requirements would find ill practical use for any scenario which calls for reallocating an existing block of memory to a larger or smaller one.
[Especially focus on pointer/reference invalidation, since that tells us more about what has to go on in memory. Iterators can make some exceptions that detach their validity from the memory representation of deque
].
Try putting yourself in the implementor's shoes. How do you implement functions like push_front
, push_back
, and expanding resize
in a way that doesn't invalidate any existing pointers to the deque
if you were ever tempted to reallocate memory blocks?
And likewise to preserve similar requirements for pop_front
and pop_back
and shrinking resize
(invalidating only pointers to the elements that were removed) if you were ever tempted to reallocate an existing memory block to a smaller size?
The gotcha part, and the one place where you might find the remotest possibility of a reallocation, is inserting to the middle of the deque
. That's the one place where all pointers to the deque
can be invalidated, and there it might be possible to reallocate the deque's
contents (possible, not necessarily practical). It is only in this particular case, as deque
implementors, where we can invalidate pointers to elements that still exist where we even have the freedom to reallocate any existing memory blocks. But it's unlikely that this will happen, since an efficient insert
implementation will typically just want to shuffle and move elements around, not actually reallocate the memory blocks in which they reside.
All these requirements combine to constrain the implementation to the type that Sutter describes, even if he kind of got sloppy there and glossed over the theoretical part. It's kind of like how C++03 code often took for granted that std::vector
was always contiguous even though it was unspecified, since the algorithmic and iterator requirements for std::vector
made a contiguous representation pretty much the only practical choice.
So in theory, it is possible that someone might sneak a reallocation somewhere, somehow, while conforming to these requirements. But in practice, it's almost impossible, and definitely impractical, so you would be hard-pressed to ever find such a deque
implementation.