Alright, so I'm trying out C++ for the first time, as it looks like I'll have to use it for an upcoming course in college. I have a couple years of programming under my belt, but not much in the non-garbage-collected world.
I have a class, a Node for use in a doubly linked list. So basically it has a value and two pointers to other Nodes. The main constructor looks like Node(const std::string & val, Node * prev, Node * next)
. The exercise includes a copy constructor that does a shallow copy of another Node, with a comment above it that says to change it to make a deep copy.
Here is what I thought that meant:
Node(const Node & other)
: value(other.value)
{
prev = new Node(other.prev->value, other.prev->prev, other.prev->next);
next = new Node(other.next->value, other.next->prev, other.next->next);
}
This seems to accomplish the goal of making it so that changing the copied Node doesn't affect the new Node. However, when I do it this way, I am allocating new stuff on the heap. This worries me, because I think it means that I should also be deleting it in the Node's destructor. But this is now inconsistent with the other constructor, where pointers to the Nodes are just passed in, already pointing to something. I can't rightly go delete
ing next
and prev
in the destructor with that going on, right?
I'm really confused, guidance appreciated!
EDIT: Here is the code (before my above change to it), as requested:
#include <string>
//! Node implements a doubly-linked list node
class Node {
friend class LinkedList; //!< LinkedList can access private members of Node
public:
//! Constructor
Node(const std::string & v, Node * p, Node * n) :
value(v), prev(p), next(n)
{
}
//! Change to deep copy
Node(const Node & other) :
value(other.value), prev(other.prev), next(other.next)
{
}
//! Read-only public methods for use by clients of the LinkedList class
const std::string & GetValue() const
{
return value;
}
Node * GetPrevious()const
{
return prev;
}
Node * GetNext()const
{
return next;
}
//! Change to deep copy
Node & operator=(const Node & other)
{
if(this!=&other)
{
value=other.value;
prev=other.prev;
next=other.next;
}
return *this;
}
private:
std::string value; //!< value stored in the node
Node * prev; //!< pointer to previous node in the list
Node * next; //!< pointer to next node in the list
};