Phillip Pearson - Second p0st

tech notes and web hackery from the guy that brought you bzero, python community server, the blogging ecosystem, the new zealand coffee review and the internet topic exchange

2003-10-13

C++ tip: always use std::list, not std::deque or std::vector, if you like storing pointers or iterators

I'm the sort of person who likes using iterators and pointers (rather than indices) to remember where I am in a list. I tend to store them in structures, then go away, modify the list, and expect them to still be valid when I come back.

That's perfectly reasonable when I'm using std::list, but it all goes to hell when using something that periodically needs reallocation. When you try to put something into a std::vector and it doesn't have space, it reallocates the whole thing and copies the old data to the new location, invalidating all your pointers.

Every time I use something other than std::list to store stuff, I end up forgetting this. And it always takes me a whole day to figure out what I've done wrong.

Oops!
... more like this: []