删除浅表的复制对象和源对象
delete shallow's copy object and the origin object
我有一个具有以下属性的类向量:
class Vector
{
private:
int _capacity;
int _size;
int _resizeFactor;
int* _elements;
使用此方法:
Vector::Vector(const Vector& other)
{
this->_size = other._size;
this->_capacity = other._capacity;
this->_resizeFactor = other._resizeFactor;
delete[] this->_elements;
this->_elements = other._elements;
}
和这个析构函数:
Vector::~Vector()
{
if (this->_elements)
delete[] this->_elements;
this->_elements = NULL;
}
在声明 on Object 后,向其插入数组并复制它,在程序结束时,会出现一个错误:
1.exe 触发了断点。
这指向以下行:
delete[] this->_elements;
在析构函数中。
如何取消仅销毁其中 1 个对象?无需更改属性类型
您需要
制作一个深层副本或沿着引用计数线实现一些东西,并且仅在删除引用相同数据的Vector
的最后一个实例时才删除elements
。
在你的复制构造函数中,你不应该delete
任何东西,因为在你调用的时候
delete[] this->_elements;
elements
还没有指向任何东西。构造函数的工作是分配内存(或者如果您真的希望将其指向other->elements
(。
首先,delete[] this->_elements;
似乎毫无意义,因为this->_elements
尚未在复制构造函数中初始化。
若要实现浅表复制,需要使用引用计数来记录引用数据的对象数,以便不会删除同一数组两次(就像现在在代码中所做的那样(。
我建议使用已经为您实现引用计数的std::shared_ptr
。为此,请将 int* 替换为 std::shared_ptr<int>
。请注意,std::shared_ptr
不会自动支持数组,因此您需要自己提供一个自定义删除器:this->_elements=std::shared_ptr<int> (new int[100], [](int *p){delete[] p;});
.然后,std::shared_ptr
将为您处理内存管理。
相关文章:
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 如何在向量列表初始化时避免对象复制以及如何延长临时的生存期
- 了解在 C++ 中分配容器时的对象复制
- C++类对象复制构造函数和运算符=
- 复制 elision/RVO 会导致从同一对象复制/移动吗?
- 如何在循环内将大对象复制到omp任务中?
- 为什么当我添加一个不同的对象(复制构造函数中的参数)时调用复制构造函数?
- 无法将类构造函数中新创建的对象复制到 C++ 中的向量成员
- 将C++对象复制到指向新指针的指针处
- 将一个 OpenCV OutputArrayOfArrays 对象复制到另一个对象
- 选择性地禁用隐式对象复制
- 不能从文件到指针向量的对象复制
- 从派生对象复制构造
- OpenCV Mat对象复制速度更快
- 将子对象复制到父对象
- 为什么普通的 c++ 编译器不优化对象复制?
- C :将一个对象复制到构造函数中的另一个对象
- 使用命名对象复制构造函数
- 不必要的对象复制 - C++ STL
- 如何将一个类的对象复制到另一个类中