gpt4 book ai didi

c++ - 在 std::set 的定义中将 const_iterator 强制转换为 iterator&

转载 作者:行者123 更新时间:2023-12-01 22:34:58 25 4
gpt4 key购买 nike

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. 为什么这个 Actor 是安全的?它将 _Rep_type::const_iterator 转换为 _Rep_type::iterator&
  2. 如何用 C++ 风格编写强制转换? I've tried to do it :static_castconst_cast 都无法完成这项工作。 reinterpret_cast 可以编译,但我不确定它是否与 C 风格的强制转换执行相同的操作。

最佳答案

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);
}

关于c++ - 在 std::set 的定义中将 const_iterator 强制转换为 iterator&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41198424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com