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();
}
}
};
我担心上面的析构函数是否会造成内存泄漏,因为我不确定调用对象的析构函数是否等同于对对象调用delete。我无法直接在对象上调用delete,因为其目的是递归删除对象的子对象。通过在delete (itr->second);
之后调用(itr->second)->~TrieTree();
,我遇到了段错误,因此我猜该对象的析构函数可能已被删除?
调用对象的析构函数是否等效于对该对象调用delete?
不,它不是等效的。
调用对象的析构函数会销毁它。
在指针上调用delete
会破坏指向的对象并释放内存。除非指向点是从new
返回的,否则行为是不确定的。