can you safely define a reference to a value stored in map, or can adding elements to a map alter the addresses of already stored values?
Printable View
can you safely define a reference to a value stored in map, or can adding elements to a map alter the addresses of already stored values?
The basic algorithm for map doesn't "need" to change the address of already stored elements, but it may do so anyways. I wouldn't rely on them having the same address in production code...
If you actually want to do that, you may want to store a pointer (for example a std::tr1::shared_ptr), and copy the pointer into some other variable - obviously, map will not change where your user-data is from a passed in pointer - it will just store the pointer together with your key.
--
Mats
As far as I know, none of the node-based containers ever reallocate a node, once it is inserted and hasn't been removed (because the container can be reordered by changing the links).
To quote section 23.1.2 of the 2003 edition of the C++ standard:Quote:
Originally Posted by m37h0d
Quote:
The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
that's what i was thinking - i couldn't see any reason why it would need to change the addresses, but i didn't want to bet on it without knowing for sure.
i already opted to go for storing a pointer. it meant i no longer had a trivial destructor, but that's no big deal.