J
JSeb
Hi there gurus,
This is a design question. Hope I'll get some insights!
Trying to get back in shape with C++, I'm writing a nice BST class. So
I have a nice class TreeNode:
template <typename T> class TreeNode
{
private:
T* mpData;
const TreeNode<T>* mpLeftChild;
const TreeNode<T>* mpRightChild;
TreeNode(const T& aData)
: mpData(&aData), mpLeftChild(NULL), mpRightChild(NULL)
{ }
// ...
};
Type T can be a huuuuuge class, so when I initialize a node with data
of this type, I make mpData point directly to the original data. That
is, I don't call type T's copy constructor.
Q1: Is that the usual approach (avoid copy constructors) when writing
a data structure?
Actually, I initially wrote
const T* const mpData;
in the declaration above. This seemed a sensible thing to do, because
I don't want the data to change while it is in the tree. Otherwise,
the tree property might become violated.
But that didn't do it. Consider for instance:
MyType data = MyType();
TreeNode<MyType> node = TreeNode(data)
data.modify()
The last line modifies the content of data, so the tree (that will
eventually contain node) might become invalid...
Q2: How does one typically deal with that king of situation? It seems
we would want the content of the data structure to be "frozen", but
only while it is in the data structure...
I think I might have a couple more seemingly basic questions, but I'll
stop here and wait for now.
Thank you!
This is a design question. Hope I'll get some insights!
Trying to get back in shape with C++, I'm writing a nice BST class. So
I have a nice class TreeNode:
template <typename T> class TreeNode
{
private:
T* mpData;
const TreeNode<T>* mpLeftChild;
const TreeNode<T>* mpRightChild;
TreeNode(const T& aData)
: mpData(&aData), mpLeftChild(NULL), mpRightChild(NULL)
{ }
// ...
};
Type T can be a huuuuuge class, so when I initialize a node with data
of this type, I make mpData point directly to the original data. That
is, I don't call type T's copy constructor.
Q1: Is that the usual approach (avoid copy constructors) when writing
a data structure?
Actually, I initially wrote
const T* const mpData;
in the declaration above. This seemed a sensible thing to do, because
I don't want the data to change while it is in the tree. Otherwise,
the tree property might become violated.
But that didn't do it. Consider for instance:
MyType data = MyType();
TreeNode<MyType> node = TreeNode(data)
data.modify()
The last line modifies the content of data, so the tree (that will
eventually contain node) might become invalid...
Q2: How does one typically deal with that king of situation? It seems
we would want the content of the data structure to be "frozen", but
only while it is in the data structure...
I think I might have a couple more seemingly basic questions, but I'll
stop here and wait for now.
Thank you!