Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the iterator of List in STL use the (*node).data instead of node->data?

I recently view the source code of SGI STL. I want to know whether I can use the "->" operator to replace the (*node).data to implement the operator*(), like this:

reference operator*() const {return (*node).data;}

replaced by:

reference operator*() const {return node->data;}

in addition:

node is a pointer which points to a struct object, like this:

template<class T>
struct __list_node {
    typedef void * void_pointer;
    void_pointer prev;
    void_pointer next;
    T data;
};
like image 282
Jeff Avatar asked Dec 22 '13 14:12

Jeff


1 Answers

In most cases (for example, when node is a pointer), these will be equivalent. The x->y operator is defined as being equivalent to (*(x)).y. However, it's possible to overload operator* or operator->, in which case they may not behave as you would expect (but they should).

As you have said, in this case node is just a pointer, so they are equivalent.

like image 73
Joseph Mansfield Avatar answered Oct 22 '22 23:10

Joseph Mansfield