[英]Stack overflow in C++ destructor
我嘗試創建detor並得到一個“Stack Overflow”我知道為什么但我想要它的工作...
#include <iostream>
#include "printTreeToFile.h"
#include "BSNode.h"
#define _BS BSNode::
#define _BSNode _BS BSNode
_BS ~BSNode()
{
Del(this);
}
void _BS Del(BSNode *x,int y)
{
if (x->isLeaf())
{
delete x;
return;
}
if (x->_Right != NULL)
Del(x->_Right,y += 1);
if (x->_Left != NULL)
Del(x->_Left,y += 1);
if (y != 1)
{
delete x;
}
return;
}
我嘗試這樣做是遞歸但刪除調用Del所以我們得到無限循環
_BS ~BSNode()
{
Del(this);
}
void _BS Del(BSNode *x,int y)
{
if (x->isLeaf())
{
delete x;
return;
}
if (x->_Right != NULL)
Del(x->_Right,y += 1);
if (x->_Left != NULL)
Del(x->_Left,y += 1);
if (y != 1)
{
delete x;
}
return;
}
你遞歸地刪除了this
。 你不需要這一切。 你過分思考。 所有你需要的是:
BSNode::~BSNode()
{
delete _Left;
delete _Right;
}
這將自動遞歸左右子樹,並停在空值處。
通過調用delete x
,您在稱為節點析構函數的函數中調用節點的析構函數。 不需要在析構函數中銷毀實際對象。
析構函數是一個允許對象釋放其擁有的資源的函數。 對象本身的破壞:
你在這里要做的是從owd析構函數中刪除對象本身。 通過這樣做,你對delete的調用將觸發對析構函數的調用,析構函數本身調用它的析構函數。
您的問題的解決方案是僅銷毀BSNode對象擁有的資源(可能是_Right和_Left)。 如果子節點沒有值,則銷毀鏈將停止。
在空指針上調用delete沒有任何效果(參見N3242的第12.4.12 節 )
在你的情況下,只需這樣做:
void _BS Del(BSNode *x)
{
delete _Right;
delete _Left
}
抱歉,我不明白你的代碼中引入了'y'變量的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.