浮生一片 2021-09-08 13:10 采纳率: 66.7%
浏览 78
已结题

【C++】TreeNode 类的析构函数有问题,tn1的析构报错,不知怎么修改,求告知[大哭]

#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;
}
  • 写回答

2条回答 默认 最新

  • 快乐鹦鹉 2021-09-08 13:12
    关注

    晕,刚才回答完,发现你删除了
    tn2,tn3先析构掉了,相当于tn1的left和right被析构掉了,然后tn1的析构的时候你再析构left和right就会报错啊
    原因你只是进行指针的赋值,没有进行深拷贝
    在构造函数中,left和right 创建新对象,然后将tn2和tn3的值赋值给left和right新建对象的值,这样就互不相关了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月21日
  • 已采纳回答 3月13日
  • 创建了问题 9月8日

悬赏问题

  • ¥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失败