首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >STL list_iterator代码问题(STL 4.0.0)

STL list_iterator代码问题(STL 4.0.0)
EN

Stack Overflow用户
提问于 2009-10-09 20:42:17
回答 2查看 429关注 0票数 2

有人能解释为什么_List_const_iterator会使用_List_node_base,并在需要的时候将其转换为_List_node吗?--我认为这背后一定有什么原因。

谢谢

代码语言:javascript
复制
struct _List_node_base
{

    _List_node_base* _M_next;   ///< Self-explanatory
    _List_node_base* _M_prev;   ///< Self-explanatory
    // ...
};

template<typename _Tp> 
struct _List_node : public _List_node_base

{
    _Tp _M_data;                ///< User's data.
};


template<typename _Tp>
struct _List_const_iterator {

    // Must downcast from List_node_base to _List_node to get to
    // _M_data.
    reference operator*() const
    { return static_cast<_Node*>(_M_node)->_M_data; }

    // ...
    // The only member points to the %list element.
    const _List_node_base* _M_node;  ///WHY NOT USING _List_node here?
};
EN

回答 2

Stack Overflow用户

发布于 2009-10-09 20:51:28

我猜测_M_node_List_node_base*类型的,因此可以使用_M_next和/或_M_prev (如您所示,它们都是_List_node_base*类型)来分配/初始化它。

我想知道为什么会有一个_List_node_base类,而不是将_M_next_M_prev声明为_List_node类的成员。一个原因可能是减少生成的代码量:如果_List_node类有许多不同的专门化,则将其大部分(如果不是全部)代码/实现放在非泛型基类中可以减少生成的代码量。

票数 2
EN

Stack Overflow用户

发布于 2012-04-29 06:15:39

这来自对EASTL list.h实现的评论-

https://github.com/paulhodge/EASTL/blob/d77d94b0d75399ac957d683ef84a8557b0f93df2/include/EASTL/list.h

代码语言:javascript
复制
/// ListNodeBase
///
/// We define a ListNodeBase separately from ListNode (below), because it allows
/// us to have non-templated operations such as insert, remove (below), and it
/// makes it so that the list anchor node doesn't carry a T with it, which would
/// waste space and possibly lead to surprising the user due to extra Ts existing
/// that the user didn't explicitly create. The downside to all of this is that
/// it makes debug viewing of a list harder, given that the node pointers are of
/// type ListNodeBase and not ListNode. However, see ListNodeBaseProxy below.
///
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1545959

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档