views:

1471

answers:

2

I'm getting the following error from g++ while trying to add iterator support for my linked list class.

LinkedList.hpp: In member function ‘Type& exscape::LinkedList::iterator::operator*() [with Type = int]’:
tests.cpp:51: instantiated from here
LinkedList.hpp:412: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘exscape::LinkedList::iterator*’

Likely relevant code snippets:

LinkedList.hpp:

template <typename Type>
class LinkedList {
    private:
        struct node {
            struct node *prev;
            struct node *next;
            Type data;
        };
    public:
        class iterator : public std::iterator<...> {
            node *p;

        public:
             Type &operator*();
        };
...
};

template <typename Type>
LinkedList<Type>::iterator::iterator(struct node *in_node) : p(in_node) {}

template <typename Type>
inline Type &LinkedList<Type>::iterator::operator*() {
    return this-p->data; ///// Line 412
}

tests.cpp:

...
LinkedList<int> l1;
...
LinkedList<int>::iterator it;
for (it = l1.begin(); it != l1.end(); ++it) {
    std::cout << "Element: " << *it << std::endl; ///// Line 51
}

I've googled (and searched SO, of course), and checked my code to no avail - either I'm missing something basic (aka. doing something stupid), or I'm missing the knowledge required. Any advice?

+1  A: 

The issue can be demonstrated by the following snippet

struct A {
  int a;
  A *get() { return this - a; }
};

int main() { A a = { 0 }; assert(&a == a.get()); }

Replace line 412 by the following

return this->p->data; // "this->" is optional
Johannes Schaub - litb
Actually, this-> is not *always* optional. When dealing with template classes that inherit from other template classes one may need it: http://www.comeaucomputing.com/techtalk/templates/#whythisarrow
Marius
@Marius, yes but here it is optional. I don't dare to try to enclose all my statements with all the exceptions found in C++ that apply to them. That wouldn't help people and it steals my time :)
Johannes Schaub - litb
+2  A: 

you're returning a reference on a temporary object : this - p->data (I emphasized the typo) computes a pointer interval, and the result of the operation is a temporary rvalue: you can't take a reference from it.

Just remove the typo:

this->p->data;
Samuel_xL
Ugh! That was it, thanks. I guess typos fall into the former category of errors... ;)