I’m implementing a vector type. I’m not troubled by the algorithms or the data structure at all but I am unsure about a remove method. for instance:
bool Remove(Node* node)
{
/* rearrange all the links and extract the node */
delete node;
}
where node is a pointer to the current node that we are at. But if I delete node then how do I prevent this from happening:
Node* currentNode = MoveToRandNode();
Remove(currentNode);
cout << currentNode->value;
If currentNode were a pointer to a pointer it would be easier but…it’s not.
Step back first. You need to define who “owns” the memory pointed to by the vector. Is it the vector itself, or the code that uses the vector? Once you define this, the answer will be easy – either Remove() method should always delete it or never.
Note that you’ve just scratched the surface of the possible bugs and you answer to “who owns it” will help with other possible issues like: