1

This is a function within my doubly linked list class, but every time I compile, I get this message: "Invalid initialization of non-const reference of type 'int&' from a temporary of type 'int'. I just can't get how else to do it.

int& LinkedList::operator[](int index)
{
    Node* current = head_;

    for(int i = 0; i < index; i++){
        current = current->getNextNode();
    }

    return(current->getValue()); // getValue() returns an int
} 

Thanks in advance!

1
  • @Beta: Then list[i] = 42 wouldn't work as expected. Commented Mar 7, 2012 at 0:47

4 Answers 4

4

Simple answer: getValue has to return an int& as well.

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to be able to use this to modify the value stored in the list, then it will have to return a reference to that value. That means that you'll need to either make Node::getValue() return a reference, or add another way to get a reference to the value stored in the node.

If you don't want to use this to modify the list contents, then you could change the return type to int.

Comments

2

The problem is that you cannot bind a non-const reference to an rvalue (in this case the temporary returned by the getValue() function). If you want to provide a reference to the value stored in the list so that it can be modified by the caller you will need to modify getValue() to return a reference.

As of the general idea, you might want to consider offering a random access operation to the list. It might give the wrong idea that it is a cheap. Users might, for example try to iterate over the list like:

for (int i = 0; i < list.size(); ++i)
    std::cout << list[i] << std::endl;

But that iteration is actually O(N^2) rather than O(N)

Comments

0

(You should, you know, just use std::list... which doesn't offer this operation for a reason...)

The reason you are returning int& is so that someone who writes mylist[i] = 42 will actually modify the contents of the list.

However, you are getting at the value by using the getValue helper which, based on the error message, returns a copy. The compiler has, by analyzing the data types, found your logical error. If you want to be able to modify the actual list data, then you have to return a reference to the actual list data, not a copy.

Thus, getValue needs to return int& as well, as Philipp suggests.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.