【发布时间】:2021-11-06 12:28:44
【问题描述】:
我正在尝试为包含指针的对象创建一个复制构造函数,该指针引用其他指针等。 下面的代码是一个二叉树。
BTree.h
{
public:
vertex* root;
BTree()
{
root = NULL;
};
~BTree() {
delete root;
root = nullptr;
};
BTree(const BTree& p_BTree) //copy constructor
{
root = new vertex(*p_BTree.root);
}
BTree& operator= (const BTree& other) //assignment operator
{
// Delete the existing class A instance
delete root;
// and create a new as a copy of other.attribute
root = new vertex(*other.root);
}
节点.h
class vertex{
public:
int key;
string data;
vertex* leftChild;
vertex* rightChild;
vertex* parent;
int height;
vertex(string data){
key = ID;
this->data = data;
leftChild = NULL;
rightChild = NULL;
parent = NULL;
ID++;
};
vertex(){
key = 0;
leftChild = NULL;
rightChild = NULL;
parent = NULL;
};
vertex(vertex* node){
key = ID;
leftChild = node->leftChild;
rightChild = node->rightChild;
parent = node->parent;
};
~vertex(){
delete leftChild;
delete rightChild;
leftChild = nullptr;
rightChild = nullptr;
};
void print(string indent){
string indent2 = indent;
cout <<indent << " " << data <<endl;
if(leftChild != nullptr || rightChild != nullptr)
{
if(leftChild != nullptr){
indent = "|" + indent;
leftChild->print(indent);
}else{
cout << indent << endl;
}
if(rightChild != nullptr){
indent2 = "|" + indent2;
rightChild->print(indent2);
}else{
cout << indent2 << endl;
}
}
}
};
#include "BTree.h"
int main() {
// Aufgabe 1
BTree B;
B.main();
// Aufgabe 2
BTree C = B; //Call copy constructor
C.print();
// Aufgabe 3
BST D;
D.main();
D.print(D.root);
D.sortvector(); //neu hinzugefügt
// Aufgabe 4
D.PrintLayers(D.root, 1);
}
问题是,当调用析构函数时,程序崩溃,因为它试图释放已经被释放的内存。
对象 B 和 C 中的根(在 main 中)具有不同的内存地址,问题是对象 C 中的左子和右子。这些是浅拷贝而不是深拷贝。我不知道如何在这些属性的复制构造函数中执行此操作。
这是它在调试器中的样子:
【问题讨论】:
-
好吧,
vertex也应该有一个复制构造函数,它可以递归地复制它的子节点。我建议您停止手动管理内存并改用std::unique_ptr,因为它旨在在编译时检测此类问题。
标签: c++ object binary-tree copy-constructor deep-copy