Const-correctness with a linked list
I am writing a class where multiple instances are linked together like a
linked list. Here's a barebones example of the relevant code:
class A
{
public:
void setNext(const A& node) { next = &node; }
const A& getNext() const { return *next; }
private:
const A* next;
}
I have declared the argument to setNext as const because node is not
modified by setNext. Class A does not modify the next node either, so the
member variable next is declared const. The problem occurs with getNext.
Whatever object obtains the next node from the current node may very well
need to modify the node, but since the member variable is const the
returned reference must be const as well.
From what I've read, const_cast usually indicates a poor design, but it
seems like I would have to use it either inside the object that obtains
the next node or use it within Class A to return a non-const reference. Is
this a valid use of const_cast or is there a flaw in my design somewhere?
And while we're on the subject, is there a preference one way or the other
on whether to return a reference or a pointer? I have setNext take a
reference to ensure I get a valid instance of A, but the returned value
could be returned either way.
No comments:
Post a Comment