[問題] C++ 判斷是不是new出來的物件
我把用到這個Tree的code補在回文裡啦…
我現在有一個class Tree,有三個成員是pointer
在copy時會new新的Tree
在destructor裡我想delete這些new出來的tree
因此我寫在解構式裡
但因為constructor 裡沒有用new,要delete用那種建構式建出的樹時就會出錯
請問是哪邊出問題了呢? 謝謝~
(如果講的不清楚我之後再補充…)
=====================================================================
class Tree{
private:
std::string root;
Tree* left_child;
Tree* right_child;
public:
//copy constructor
Tree(const Tree& tree):left_child(0),right_child(0){
if(tree.left_child != 0)
left_child = new Tree(*tree.getLeftChild());
if(tree.right_child!= 0)
right_child = new Tree(*tree.getRightChild());
}
//用下面這種建構式建出的樹 delete會出錯
//constructor
Tree(std::string in_root, Tree &in_left, Tree &in_right):
root(in_root),left_child(&in_left),right_child(&in_right){}
~Tree(){
if(left_child!=0)
delete left_child;
if(right_child!=0)
delete right_child;
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 175.96.117.5
→
09/22 22:40, , 1F
09/22 22:40, 1F
推
09/22 22:40, , 2F
09/22 22:40, 2F
→
09/22 22:41, , 3F
09/22 22:41, 3F
→
09/22 22:41, , 4F
09/22 22:41, 4F
→
09/22 22:46, , 5F
09/22 22:46, 5F
→
09/22 23:21, , 6F
09/22 23:21, 6F
→
09/22 23:21, , 7F
09/22 23:21, 7F
→
09/22 23:25, , 8F
09/22 23:25, 8F
推
09/22 23:32, , 9F
09/22 23:32, 9F
→
09/22 23:33, , 10F
09/22 23:33, 10F
→
09/22 23:34, , 11F
09/22 23:34, 11F
→
09/22 23:35, , 12F
09/22 23:35, 12F
→
09/22 23:39, , 13F
09/22 23:39, 13F
→
09/22 23:40, , 14F
09/22 23:40, 14F
→
09/22 23:44, , 15F
09/22 23:44, 15F
→
09/22 23:45, , 16F
09/22 23:45, 16F
→
09/23 00:38, , 17F
09/23 00:38, 17F
→
09/23 00:39, , 18F
09/23 00:39, 18F
→
09/23 00:39, , 19F
09/23 00:39, 19F
→
09/23 01:27, , 20F
09/23 01:27, 20F
→
09/23 01:29, , 21F
09/23 01:29, 21F
※ 編輯: wagaru 來自: 175.96.117.5 (09/23 01:50)
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 4 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章
11
38