Question with STL list_iterator code (STL 4.0.0)

Can anyone explain why the _List_const_iterator will use the _List_node_base and drag and drop it into the _List_node if needed? - I think there must be some reason for this.

thank

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

      

+2


source to share


2 answers


I am assuming it _M_node

has a type _List_node_base*

, so it can be assigned / initialized with _M_next

and / or _M_prev

(which you have shown has a type _List_node_base*

).



I wonder why there is a class _List_node_base

at all, instead of being declared _M_next

and _M_prev

as members of the class _List_node

. One reason might be to reduce the amount of generated code: if you have many different class specializations _List_node

, most (if not all) of its code / implementation in the non-core base class will reduce the amount of generated code.

+2


source


This is from the comment on the 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.
///

      

+1


source







All Articles