const_iterator对迭代器的投射,以及std :: set的定义

问题描述 投票:4回答:1

C ++ STL使用红黑树在std::setstd::map内部存储数据。我注意到set::iterator实际上是红黑树的const迭代器的typedef:

//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;

这是合理的,因为应该假定用户不要通过迭代器来修改集合的内容。但是set必须实现inserterase之类的操作,它们需要红黑树的非常量迭代器。 SGI STL使用c样式强制转换来做到这一点:

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

我想知道:

  1. 为什么这个演员安全?正在将_Rep_type::const_iterator强制转换为_Rep_type::iterator&
  2. 如何用C ++风格编写演员表? I've tried to do itstatic_castconst_cast均不起作用。 reinterpret_cast可以编译,但是我不确定它是否与C样式强制转换相同。
c++ casting stl iterator set
1个回答
0
投票

iterator_Rep_type::iterator是相同类模板的实例,前者使用const限定类型,而后者使用相同但非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);
}
© www.soinside.com 2019 - 2024. All rights reserved.