Including const_iterator in an iterator and defining std :: set

C ++ STL uses a red-black tree to store data inside std::setand std::map. I noticed that it set::iteratoris actually a typedef of a constant mahogany iterator:

//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 should not modify the contents of the set through an iterator. But I setmust implement such operations as insertand erase, which calls a non-constant iterator of red-black tree. SGI STL uses c-style for this:

void erase(iterator __position) { 
  typedef typename _Rep_type::iterator _Rep_iterator;
  _M_t.erase((_Rep_iterator&)__position); 
}

I am wondering:

  • Why is this cast safe? He throws _Rep_type::const_iteratoron _Rep_type::iterator&.
  • ++? : static_cast, const_cast . reinterpret_cast , , , C-.
+4
1

iterator _Rep_type::iterator , const, - , non- const. :

template <class T, class U>
struct B {};

using S = B<int&, int*>;
using Sconst = B<const int&, const int*>;

, :

  1. , .
  2. static_cast, . , reinterpret_cast:
int test() {
    S s;
    Sconst& sconst = reinterpret_cast<Sconst&>(s);
}
0

Source: https://habr.com/ru/post/1664041/


All Articles