Re: [問題] C++ 判斷是不是new出來的物件

看板C_and_CPP (C/C++)作者 (wagaru)時間14年前 (2011/09/23 01:48), 編輯推噓1(101)
留言2則, 1人參與, 最新討論串3/4 (看更多)
補一下我應用的例子好了… 不過剛剛省略了一個建構子 Tree(std::string in_root):root(in_root),left_child(0),right_child(0){} ================= TreeParser.cpp ================= Tree buildTreeFromString(std::string str){ ...... //如果是葉子,也就是left_child,right_child都是空 if(isLeaf()){ std::string root = ... Tree tree(root); <--------剛剛省略了這個建構子,補在下面 return tree; } //有左小孩與右小孩,也就是left_child,right_child不為空 else if(...){ std::string root = ... Tree l_child(buildTreeFromString(...)); Tree r_child(buildTreeFromString(...)); Tree tree(root,l_child,r_child); return tree; } } 我在想 在local的tree要回傳時會呼叫copy constructor拷貝一份,所以會用到new 而local的tree要釋放時有可能沒有new出來的物件,所以會出錯…吧… ※ 引述《wagaru (wagaru)》之銘言: ===================================================================== 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 ※ 編輯: wagaru 來自: 175.96.117.5 (09/23 01:51)

09/23 02:06, , 1F
這樣的話上篇大家其實都猜到問題點了
09/23 02:06, 1F

09/23 02:07, , 2F
解決方法就是請把所有的 Tree 都用 new 的要來就好
09/23 02:07, 2F
文章代碼(AID): #1EUtJcsJ (C_and_CPP)
文章代碼(AID): #1EUtJcsJ (C_and_CPP)