mercredi 25 mars 2015

before_begin implementation of forward_list

How is the before_begin method implemented in the context of a std::forward_list?


I have tried something like this:



template <class _Tp>
typename forward_list<_Tp>::iterator forward_list<_Tp>::before_begin() NOEXCEPT {
return forward_list_iterator<_Tp>(new forward_list_node<_Tp>(_Tp(), m_pHead));
}

template <class _Tp>
typename forward_list<_Tp>::const_iterator forward_list<_Tp>::before_begin() const NOEXCEPT {
return forward_list_const_iterator<_Tp>(new forward_list_node<_Tp>(_Tp(), m_pHead));
}


What I understood is that the before_begin method shall be used when calling insert_after emplace_after etc. Thus I made the method return an iterator to a new node that points to m_pHead and has a default value for the template type _Tp. However, I am unsure about two things:


1) As I am using templates, how can I get the default value? Is _Tp() a legal expression in order to get the default value for the specific type (with both primitive and user-defined types)?


2) As this method returns an iterator before m_pHead, if I call one of the insert_after overloaded methods with before_begin as the first argument, wouldn't I end up having the data inserted in the list, but without having the m_pHead updated?


My implementation of (one of the four overloads of) insert_after is as follows:



template <class _Tp>
void forward_list<_Tp>::insert_after(const_iterator _position, const _Tp& _value) {
forward_list_node<_Tp>* _node = new forward_list_node<_Tp>(_value, _position.m_pNode->m_pNext);
_position.m_pNode->m_pNext = _node;
}


Thank you very much for taking your time. :)


Aucun commentaire:

Enregistrer un commentaire