我让我的树的插入函数创建了一个包含数据参数的深层拷贝的新节点。
block 1:
insert(Object* toInsert){
...
Node temp;
temp->data = new Object(*toInsert); //deep copy toInsert
...
}
我认为这是更可靠的实现,因为它避免了隐私泄露。然而,这导致了内存泄漏,因为另一个组件(由教授给出)没有删除它传递给 insert() 的对象。我的析构函数会正确释放节点,但不会释放传递给 insert() 的原始数据。
我通过将代码更改为 block 2 来修复内存泄漏。
第 2 部分:
insert(Object* toInsert){
...
Node temp;
temp->data = toInsert; //directly toInsert to data
...
}
我想到了第三种解决方案,但决定我的插入函数不应管理另一个组件的内存。
block 3:
insert(Object* toInsert){
...
Node temp;
temp->data = new Object(*toInsert); //deep copy toInsert
delete toInsert; //manages another component's memory
...
}
我的直觉告诉我 Block 3 是不行的。我说得对吗?
在处理数据结构时,是像 Block 2 那样直接插入数据还是像 Block 1 那样进行深拷贝更好?
谢谢
最佳答案
选择接口(interface)函数的签名,以便它们对与所有权转移有关的参数的处理是明确的。
对于选项 1,函数复制输入参数,通过(常量)引用而不是通过指针传递对象:
insert(const Object& toInsert){
...
Node temp;
temp->data = new Object(toInsert); //deep copy toInsert
...
}
对于选项 2,函数假定参数对象的所有权,通过 std::unique_ptr
传递对象:
insert(std::unique_ptr<Object> toInsert){
...
Node temp;
temp->data = toInsert.release();
...
}
选项 3 没有意义。
关于c++ - 将数据插入数据结构时是深拷贝还是浅拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40189146/