Redian新闻
>
一个Naive的问题,tree的destruction
avatar
一个Naive的问题,tree的destruction# JobHunting - 待字闺中
D*f
1
有点太简单,都不好意思放上来,就是帮我看看这个destructor会不会有内存泄漏?我
觉得似乎要来个delete this?
在constructor里new了一堆Node按照树结构组织好。
class SuffixNode
{
public:
SuffixNode(const char*);
~SuffixNode();
private:
SuffixNode* pFirstChild;
SuffixNode* pNextSibling;
};
SuffixNode::~SuffixNode()
{
SuffixNode* pNode = pFirstChild;
SuffixNode* pToDelete = 0;
while(pNode)
{
pToDelete = pNode;
pNode = pNode->pNextSibling;
delete pToDelete;
}
}
int main()
{
const char* s = "Hello world!";
SuffixNode* pRoot = new SuffixNode(s);
delete pRoot;
}
avatar
h*f
2
I don't see the code for the constructor.
Assuming there is no cyclic formed by any SuffixNode and you default
pFirstChild and pNextSibling to NULL if they don't point to anything, you
can just write:
SuffixNode::~SuffixNode()
{
delete pFirstChild;
delete pNextSibling;
}
You can also easily verify by using valgrind in any case.
avatar
D*f
3
谢谢了,的确比我的简单多了。
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。