删除关键词c++

问题描述 投票:0回答:1

我有一个类,它有2个bool和一个指针数组,我在堆上分配,问题是当它调用destructor时,它给我一个错误,可能是因为它删除的太多了,我看到它试图访问0xdddddddd,并向我显示 "Exception thrown: read access violation.this was 0xDEEEDEEF."。

1.如何更好的使用 "delete",是不是因为操作符过载?

2.另外它说我没有初始化 "QuadTree::childs",为什么?

class QuadTree {
public:
QuadTree* childs[4];
    bool info;
    bool parent;

QuadTree() {
    for (int i = 0; i < 4; ++i) {
         childs[i]=NULL;
    }
    info = false;
    parent = false;
}


~QuadTree() {
    for (int i = 0; i < 4; ++i) {
            delete childs[i];
    }
}
    QuadTree& operator=(const QuadTree& tree) {

    for (int i = 0; i < 4; ++i) {
        childs[i] = new QuadTree;
        if (tree.childs[i]->parent == 1) {
            childs[i] = tree.childs[i];
        }
        childs[i]->info = tree.childs[i]->info;
        childs[i]->parent = tree.childs[i]->parent;
    }
    return *this;
 }
}

所以这是添加两棵树的代码,我创建重载操作符是为了下一个原因,如果一棵树的节点是白色的,另一棵树是父节点,我只想复制父节点。

void addTrees(const QuadTree& tree1, const QuadTree& tree2, QuadTree& end) {

if (tree1.info == 1 || tree2.info == 1) {
    end.info = 1;
    return;
}
else if (tree1.parent == 1 && tree2.parent == 1) {
    end.parent = 1;
    for (int i = 0; i < 4; ++i) {
        end.childs[i] = new QuadTree;
        addTrees(*tree1.childs[i], *tree2.childs[i], *end.childs[i]);
    }


}
else if (tree1.parent == 1) {
    end.parent = 1;
    end = tree1;

}
else if (tree2.parent == 1) {
    end.parent = 1;
    end = tree2;

}
else {
    end.info = 0;
}


}
c++ memory heap destructor
1个回答
1
投票

这一行 childs[i] = tree.childs[i]; 并没有做你认为的事情。

你现在引用的是他们分配的内存,不再引用你分配的内存。不管谁想秒删这个内存,都会有不好的结果。

如果你想把他们的子代复制到你最近分配的子代中,你就需要去引用指针,对对象本身进行操作。*childs[i] = *tree.childs[i]


1
投票

问题出在你的assigmnent操作符上。

    QuadTree& operator=(const QuadTree& tree) {

        for (int i = 0; i < 4; ++i) {
            childs[i] = new QuadTree;
            if (tree.childs[i]->parent == 1) {
                childs[i] = tree.childs[i];
            }
            childs[i]->info = tree.childs[i]->info;
            childs[i]->parent = tree.childs[i]->parent;
        }
        return *this;
    }
};

在这些行文中。

if (tree.childs[i]->parent == 1) {
    childs[i]->info = tree.childs[i]->info;
            childs[i]->parent = tree.childs[i]->parent;

childs[i] maybe a nullptr 赋值是可以的,但解引用就不行了。

而对于 ->parent 你做防卫 nullptr

请检查 nullptr 在解围前。

© www.soinside.com 2019 - 2024. All rights reserved.