Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers to elements of STL containers

Tags:

Given an STL container (you may also take boost::unordered_map and boost::multi_index_container into account) that is non-contiguous, is it guaranteed that the memory addresses of the elements inside the container never changes if no element is removed, (but new ones can be added)?

e.g.

class ABC { }; // //... // std::list<ABC> abclist; ABC abc; abclist.insert(abc); ABC * abc_ptr = &(*abclist.begin()); 

In other word will abc_ptr be pointed to abc throughout the execution, if I do not remove abc from abc_list.

I am asking this because I am going to wrap the class ABC in C++/Cli, so I need pointers to the ABC instances in the wrapper class. ABC is a simple class and I want the container to handle the memory. If the answer is no then I will use std::list<ABC*>.

like image 670
ali_bahoo Avatar asked Mar 03 '11 14:03

ali_bahoo


2 Answers

std::list, std::set, and std::map guarantee that the iterators (including simple pointers) will not be invalidated when a new element is added or even removed.

like image 161
Armen Tsirunyan Avatar answered Sep 19 '22 16:09

Armen Tsirunyan


As Armen mentioned std::list, std::set, and std::map are guaranteed to only invalidate the removed iterator. In the case of boost::unodered_map, the modifiers may indeed invalidate iterators.

http://www.boost.org/doc/libs/1_38_0/doc/html/boost/unordered_map.html

like image 33
milky414 Avatar answered Sep 20 '22 16:09

milky414