2

More specifically, I am wondering why we use pointers in a typical linked list implementation. Are there any problems that the following implementation of a Node might cause?

template <typename T>
class Node {
    T data;
    Node<T>& next;
    Node<T>& prev;
};

Is there some reason we should use pointers here instead of references?

7
  • What if the next or previous node isn't? Commented Sep 14, 2012 at 22:41
  • 1
    This list implementation works great on my Turing machine. Commented Sep 14, 2012 at 22:41
  • A reference can't be null, so you'd need some way of representing invalid/nonexistent 'next' and/or 'prev'. Commented Sep 14, 2012 at 22:42
  • That would work if you wanted an infinite list :P Commented Sep 14, 2012 at 22:43
  • Theoretically could you not just make a constant null node to point to at the end of the list? Not suggesting this is a good idea, mind you! Commented Sep 14, 2012 at 22:45

2 Answers 2

4

You can't set references after creating them, which makes a non-mutable linked-list implementation somewhat tricky. (You'd need to wrap the references in objects that you can re-crate when you want to change the reference).

There's also no way to set a NULL value on a reference, so representing the ends of your list would require some imagination.

Probably better to stick to pointers in a linked list, or even better, use std::list<>.

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

1 Comment

Or better still, don't use a linked list at all, unless you're just trying to learn how pointers work...
1

Lvalue references can't replace pointers; they do different things.

An lvalue reference must be initialized with an lvalue and the lvalue reference will refer to that object for the rest of it's lifetime. It cannot be rebound. This presents two immediate problems for your list node.

How do you start the list? You want to construct a node that has no "previous" yet the prev member must be initialized with a Node object. You could conceivably use a Node whose prev is it self to represent the head of a list, but this is working around the poor choice of lvalue reference. (E.g. Node<T> emptylist = { T(), emptylist, emptylist }; //eurgh)

Second, how do you manipulate the list? You can't change the bindings of next and prev meaning that the only way to alter the list would be to construct a completely new set of nodes and copy every single data element.

1 Comment

"A reference must be initialized with an lvalue" -- well... not really. int const& cr = 5; int&& rv = 5;

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.