#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;
}
晕,刚才回答完,发现你删除了
tn2,tn3先析构掉了,相当于tn1的left和right被析构掉了,然后tn1的析构的时候你再析构left和right就会报错啊
原因你只是进行指针的赋值,没有进行深拷贝
在构造函数中,left和right 创建新对象,然后将tn2和tn3的值赋值给left和right新建对象的值,这样就互不相关了
找到啦,构造函数定义错了,传参的时候传成指针就对啦
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;
std::size_t* num;
};
void testTreeNode() {
TreeNode* tn2 = new TreeNode("World", 1025);
TreeNode* tn3 = new TreeNode("!", 1025);
TreeNode tn1("Hello", 1024, tn2, tn3);
TreeNode tn4("dream", 1024, tn2, tn3);
tn1 = tn4;
cout << "end...\n";
}