删除浅表的复制对象和源对象

delete shallow's copy object and the origin object

本文关键字:对象 复制 删除      更新时间:2023-10-16

我有一个具有以下属性的类向量:

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将为您处理内存管理。