class TrieTree{
private:
string ch;
unordered_map<string, TrieTree*> child;
public:
TrieTree(string val): ch(val){}
~TrieTree(){
for(unordered_map<string, TrieTree*>::iterator itr = this->child.begin();
itr != this->child.end();
itr++){
(itr->second)->~TrieTree();
}
}
};
I'm concerned if the above destructor will create memory leak since I'm unsure if calling an object's destructor is equivalent to calling delete to the object. I cannot directly call delete on the object since the intention is to recursively delete the object's child. By calling delete (itr->second);
after (itr->second)->~TrieTree();
I'm getting segmentation faults, so I'm guessing the object might have been deleted after its destructor?
Is calling an object's destructor equivalent to calling delete on the object?
No, it is not equivalent.
Calling destructor of an object destroys it.
Calling delete
on a pointer destroys the pointed object and deallocates the memory. Behaviour is undefined unless the pointed was returned from allocating new
.
If you allocate memory with new
and only call the destructor without deallocating, then you will leak memory. If you destroy the object and attempt to use delete
while the pointed object is destroyed, then the behaviour of your program will be undefined.
P.S. Avoid using owning bare pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With