Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc list node swap implementation overcomplicated?

Tags:

c++

list

gcc

I'm using the SGI STL (GCC) as a reference for a custom library, and while digging into std::list::swap() came across the following implementation,

Note: This method does not handle adjacent nodes properly.

// namespace std {
// namespace __detail {
void
_List_node_base::swap(_List_node_base& __x, _List_node_base& __y) throw()
{
  if ( __x._M_next != &__x )
    {
      if ( __y._M_next != &__y )
        {
          // Both __x and __y are not empty.
          std::swap(__x._M_next,__y._M_next);
          std::swap(__x._M_prev,__y._M_prev);
          __x._M_next->_M_prev = __x._M_prev->_M_next = &__x;
          __y._M_next->_M_prev = __y._M_prev->_M_next = &__y;
        }
      else
        {
          // __x is not empty, __y is empty.
          __y._M_next = __x._M_next;
          __y._M_prev = __x._M_prev;
          __y._M_next->_M_prev = __y._M_prev->_M_next = &__y;
          __x._M_next = __x._M_prev = &__x;
        }
    }
  else if ( __y._M_next != &__y )
    {
      // __x is empty, __y is not empty.
      __x._M_next = __y._M_next;
      __x._M_prev = __y._M_prev;
      __x._M_next->_M_prev = __x._M_prev->_M_next = &__x;
      __y._M_next = __y._M_prev = &__y;
    }
}

This looks to me as if it could be simplified to,

void
_List_node_base::swap(_List_node_base& __x, _List_node_base& __y) throw()
{
  _List_node_base* __xnext = __x._M_next;
  _List_node_base* __xprev = __x._M_prev;
  _List_node_base* __ynext = __y._M_next;
  _List_node_base* __yprev = __y._M_prev;

  __xnext->_M_prev = __xprev->_M_next = &__y;
  __ynext->_M_prev = __yprev->_M_next = &__x;
  std::swap(__x._M_next,__y._M_next);
  std::swap(__x._M_prev,__y._M_prev);
}

I've tested this for all cases (empty/empty, empty/not-empty, etc.), including __x and __y referencing the same node, and it seems to work, however, my trust in the SGI codebase is making me doubt myself.

So my question is: Is this correct? And if so is there any benefit to using the longer version?

Thank you.

like image 566
Johnny Cage Avatar asked Aug 28 '26 09:08

Johnny Cage


1 Answers

Self-assignment checks were all the rage. They're known to be pessimizations and bug-hiding now. You may want to find a more modern source of inspiration.

like image 105
Puppy Avatar answered Aug 29 '26 22:08

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!