My last post tried to address the issue of storing pointers to objects in other objects without having to worry about what gets destroyed first, and who's going to be destroying it.
[ A ] Problems
Thanks to arithma's input and some experimentation, it is clear that the solution I presented has shortcomings. By depending on a clone() function to make copies of the object being passed, I exclude a large amount of functionality from my program.
Consider the following Node class in a hypothetical linked list implementation:
class Node
{
public:
explicit Node(const int data, const Node* next);
Node* clone() const;
~Node();
Node* getNextAddr();
private:
int _data;
Node* _next;
};What would happen if we used the previous method to construct a linked list out of two Nodes?int main(int argc, char **argv)
{
Node na(1, 0); // The next element is the end of the list
Node nb(2, &na);
cout << "na is really at: " << &na << endl;
cout << "na appears to be at: " << nb.getNextAddr() << endl;
return 0;
}
Running the above code, you will notice that to nb, the next element in the list appears to be at an address that is different from the address of na. This is because nb stores its own copy of the next node instead of simply pointing to it.
[ B ] Revisiting Ownership
You might think that such a problem is consistent with what we were trying to achieve. After all, the relationship between nodes in a linked list isn't really ownership.
However, we still need to manage those nodes somehow. What happens when you destroy a node in the middle of the chain? What happens when you destroy the first node in the chain? These are all problems that cannot be resolved with our previous method of enforcing ownership. We've only managed to solve the problem for a limited number of cases.In my next post I'll discuss a different way of thinking about ownership, and try to demonstrate that it covers a wider range of situations where we might need to pass an object to another object, and not worry about having to keep track of it. If you would like to try the code in this post, please let me know and I can send you an implementation.
0 comments:
Post a Comment