开发者

STL list_iterator code question (STL 4.0.0)

开发者 https://www.devze.com 2022-12-08 00:09 出处:网络
Can anyone explain why the _List_const_iterator would be using _List_node_base and downcast it to _List_node when needed? -- I think there must be some reason behind this.

Can anyone explain why the _List_const_iterator would be using _List_node_base and downcast it to _List_node when needed? -- I think there must be some reason behind this.

Thanks

struct _List_node_base
{

    _List_node_base* _M_next;   ///< Self-explanatory
    _List_node_base* _M_prev;   ///< Self-e开发者_运维问答xplanatory
    // ...
};

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


I'm guessing that _M_node is of type _List_node_base* so that it can be assigned/initialized using _M_next and/or _M_prev (which as you've shown are of type _List_node_base*).

I wonder why there's a _List_node_base class at all, instead of declaring _M_next and _M_prev as members of the _List_node class. One reason might be to reduce the amount of generated code: if you have many different specializations of the _List_node class, having most (if not all) of its code/implementation in a non-generic base class reduces the amount of generated code.


This is from the comment on EASTL list.h implementation-

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

/// 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.
///
0

精彩评论

暂无评论...
验证码 换一张
取 消