Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling an object's destructor equivalent to calling delete on the object?

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?

like image 814
John Liu Avatar asked Mar 02 '23 22:03

John Liu


1 Answers

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.

like image 116
eerorika Avatar answered Mar 05 '23 19:03

eerorika