list<T>, does it ever reallocate?

Hi everyone,

I am facing the following problem. I have a class with two list container and a map that somehow puts elements of the first list in relation with elements of the second list. Imagine something like

list<A> list_one;
list<B> list_two;

map<A*, list<B*> > my_map; //relation between elements of list_one and list_two

Obviously in this construction I would like to have guaranteed that the elements of the list will never change their location. I don't see any reason why the list container should move around elements in the memory, but: Do I have some sort of guarantee that this will not happen on any implementation of C++ ?
You do not have such guarantee in the standard of C++, so theoretically it is unsafe. However, I haven't heard of any list implementation that moved objects in memory, so in practice you can do this.
You'll have to be especially careful in the use of such a map to not make a copy of the lists. For example, you'll always have to reference the second element by reference. It's an easy and costly mistake to not do so throught a large program.

The normal way to make such guarantees is to use pointer to a list as in:
map<A*, *list<B*> >
note that list<B*> and list<B> (list_two;) are not compatible. maybe you mean this: map<A*, list<B> *> then you have a pointer to a list (list_two) and you don't have to worry about what the list pointed to does but you have to worry whether that object pointed to exists or not
coder777 +1

The standard containers are free to reallocate their objects, but they won't touch referenced stuff.

list <Foo> A Foo object may be copy constructed and freed at will (i.e, its memory location may be changed).

list <Foo*> The list does not manipulate Foo objects. It manipulates pointers to Foo objects. Hence, the Foos will always be in exactly the same place you put them. (The pointers may be stored in different places in memory.)

In both cases, the relative ordering of the elements in the list never changes.

Hope this helps.
Topic archived. No new replies allowed.