我正在嘗試建立一個由保存指向物件的指標的節點組成的二叉樹,但是在我的“清除樹”函式中,我在嘗試釋放節點內指標處的記憶體時遇到了讀取訪問沖突。為什么當我在根指標處釋放記憶體時沒有拋出例外,但在節點內的 int 指標處有?
拋出例外:讀取訪問沖突。 它是0x2。
class Tree {
private:
struct Node {
int* val = nullptr;
Node* right = nullptr;
Node* left = nullptr;
};
Node* root = nullptr;
public:
bool Insert(int* num);
void Empty();
bool isEmpty() const;
};
void Tree::Empty()
{
while (!(root == nullptr)) // Just handling the simplest case for now
{
if (root->left == nullptr && root->right == nullptr)
{
delete root->val; // Read access violation
delete root;
root = nullptr;
break;
}
[...]
}
}
bool Tree::Insert(int* num)
{
Node* insertion = new Node;
int* temp = new int(*num);
insertion->val = temp;
if (root == nullptr)
{
root = insertion;
return true;
}
Node* c_node = root;
while (true)
{
if (*temp == *c_node->val)
{
delete temp;
delete insertion;
return false;
}
if (*temp > *c_node->val)
{
if (c_node->right != nullptr)
{
c_node = c_node->right;
continue;
}
c_node->right = insertion;
return true;
}
if (c_node->left != nullptr)
{
c_node = c_node->left;
continue;
}
c_node->left = insertion;
return true;
}
}
int main()
{
int a = 2;
Tree my_tree;
my_tree.Insert(&a);
my_tree.Empty();
}
我很感激任何反饋!
uj5u.com熱心網友回復:
我建議從Node對自己的內容負責:
struct Node {
Node(int *val) : val(new int(*val)) { }
int* val = nullptr;
Node* right = nullptr;
Node* left = nullptr;
~Node() { delete val; }
};
完成此操作后,我們可以通過讓Empty(and Insert) 處理其存盤的值來稍微簡化(and )的代碼,Empty因此到目前為止您實作的片段最終是這樣的:
void Tree::Empty()
{
while (!(root == nullptr)) // Just handling the simplest case for now
{
if (root->left == nullptr && root->right == nullptr)
{
delete root;
root = nullptr;
break;
}
}
}
至于使這個實作適用于具有多個節點的樹,我可能會遞回執行:
void Tree::Empty(Node *node)
{
if (node == nullptr)
return;
Empty(node->left);
Empty(node->right);
delete node;
}
我可能還會為 定義一個 dtor Tree,因此用戶不需要顯式呼叫Empty(實際上,我可能會將其設為Empty私有,因此外界根本無法呼叫它,但這是一個單獨的問題)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/384340.html
上一篇:在字典中存盤值
