C++ STL uses a red-black tree to store data inside std::set
and std::map
. I noticed that set::iterator
is actually a typedef of the const iterator of the red black tree:
//All code snippets taken from SGI STL. https://www.sgi.com/tech/stl/
typedef _Rb_tree<key_type, value_type, _Identity<value_type>, key_compare, _Alloc> _Rep_type;
typedef typename _Rep_type::const_iterator iterator;
This is reasonable because users are supposed not to modify the content of the set through an iterator. But set
has to implement operations like insert
and erase
, which calls for a non-const iterator of the red-black tree. SGI STL uses a c-style cast to do this:
void erase(iterator __position) {
typedef typename _Rep_type::iterator _Rep_iterator;
_M_t.erase((_Rep_iterator&)__position);
}
I'm wondering:
- Why is this cast safe? It is casting
_Rep_type::const_iterator
to_Rep_type::iterator&
. - How to write the cast in C++ style? I've tried to do it: Neither
static_cast
norconst_cast
will do the job.reinterpret_cast
can compile, but I'm not sure if it does the same thing as the C-style cast.