Reputation: 390
I don't know how to word my question simpler, but say I have this:
class Curve;
class Node {
Curve *curve;
public:
Node(Curve *curve);
~Node();
}
class Curve {
LinkedList<Node> nodes;
public:
Curve(); ~Curve();
}
Is it okay to not delete the pointer to the curve in the destructor ~Node
? That is, will it cause a memory leak? Or am I supposed to delete it? If I delete it, will it destroy the curve?
Edit: The curve will get deleted eventually.
Edit 2: Implementation.
Say I implement code below:
int main() {
Curve *curve = new Curve();
Node *node = new Node(curve);
delete node; delete curve;
return 0;
}
Will I still need to call delete curve
within the node's destructor?
Upvotes: 0
Views: 300
Reputation: 415
As mentioned in other answers, this is about ownership. In your particular example it is ok to not delete Curve* in destructor of the Node class, because you manage the life of Curve instance in main function. In real code managing raw pointers can be quite difficult and lead to nasty errors. Since you tagged the question as C++, you should use standard library's smart pointer and replace Curve* with std::shared_ptr. In case you change your mind and make Node solely responsible for managing the Curve instance it is a good idea to use std::unique_ptr instead of raw pointer.
Upvotes: 3
Reputation: 385108
This is not about memory fragmentation, or memory leaks.
This is about:
main
(which shares it with the Node
) or Node
(to which main
transfers ownership)? You need to somehow make that clear, either by using smart pointers or via documentation.Upvotes: 3