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<Type>::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<int>::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
  • 5
    Looks like you might have a typo on line 412 Commented Nov 20, 2009 at 19:55

2 Answers 2

5

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

Ugh! That was it, thanks. I guess typos fall into the former category of errors... ;)
2

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 

2 Comments

Actually, this-> is not always optional. When dealing with template classes that inherit from other template classes one may need it: comeaucomputing.com/techtalk/templates/#whythisarrow
@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 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.