#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <memory>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::shared_ptr;
class TreeNode {
public:
TreeNode() :count(0), left(nullptr), right(nullptr), num(new std::size_t(1)) {}
TreeNode(const string& str, int c) :value(str),count(c), left(nullptr), right(nullptr), num(new std::size_t(1)) {}
TreeNode(const string& str, int c, TreeNode& lnode, TreeNode& rnode) :value(str), count(c), left(&lnode), right(&rnode), num(new std::size_t(1)) {}
TreeNode(const TreeNode& tn) :value(tn.value), count(tn.count), left(tn.left), right(tn.right) { ++* num; }
~TreeNode() {
if (-- * num == 0) {
delete left;
delete right;
delete num;
}
}
TreeNode& operator=(const TreeNode& tn) {
++* tn.num;
if (-- * num == 0) {
delete left;
delete right;
delete num;
}
value = tn.value;
count = tn.count;
left = tn.left;
right = tn.right;
return *this;
}
private:
string value;
int count;
TreeNode* left;
TreeNode* right;
//模拟引用计数,*num为0则销毁对象
std::size_t* num;
};
void testTreeNode() {
TreeNode tn2("World", 1025), tn3("!",1026);
TreeNode tn1("Hello", 1024, tn2, tn3);
//tn1 = tn3;
}
int main(){
testTreeNode();
cout << "end...\n";
return 0;
}
【C++】TreeNode 类的析构函数有问题,tn1的析构报错,不知怎么修改,求告知[大哭]
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- 快乐鹦鹉 2021-09-08 13:12关注
晕,刚才回答完,发现你删除了
tn2,tn3先析构掉了,相当于tn1的left和right被析构掉了,然后tn1的析构的时候你再析构left和right就会报错啊
原因你只是进行指针的赋值,没有进行深拷贝
在构造函数中,left和right 创建新对象,然后将tn2和tn3的值赋值给left和right新建对象的值,这样就互不相关了本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
- ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
- ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
- ¥15 cmd cl 0x000007b
- ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
- ¥500 火焰左右视图、视差(基于双目相机)
- ¥100 set_link_state
- ¥15 虚幻5 UE美术毛发渲染
- ¥15 CVRP 图论 物流运输优化
- ¥15 Tableau online 嵌入ppt失败