2017-11-11 144 views
0

我有属性的类向量:删除浅的复制对象和原始对象

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; 
} 

后声明对象,将数组插入并复制它,在程序结束时出现错误:

1.exe has triggered a breakpoint.

that points to the line:

delete[] this->_elements; 

in the destructor.

我怎样才能取消销毁只有1个对象? 不改变属性类型

+2

你有没有考虑使用'标准:: shared_ptr'? – Arash

+0

您为什么使用'这 - >' –

+0

如果我正确理解,不具有效果 – arik

回答

1

您需要可以进行深度复制或沿引用计数的行执行的东西,只有当一个Vector引用相同数据的最后一个实例被删除,删除elements

在你的拷贝构造函数你不应该delete任何东西,因为点在哪里,你叫

delete[] this->_elements; 

elements尚未指向任何东西。分配内存是构造函数的工作(或者如果你真的希望它指向other->elements)。

1

首先,delete[] this->_elements;似乎毫无意义,因为this->_elements尚未在复制构造函数中初始化。

要实现浅拷贝,你需要使用引用计数,使许多对象是如何引用数据的记录,让您不删除同一阵列的两倍(就像你在你的代码,现在做什么)。

我建议使用std::shared_ptr其中已经实施的引用计数为您服务。为此,请用std::shared_ptr<int>替换int *。请注意,std::shared_ptr不会自动支持阵列,因此您需要自行提供自定义删除器:this->_elements=std::shared_ptr<int> (new int[100], [](int *p){delete[] p;});。然后,std::shared_ptr将为您处理内存管理。

+0

谢谢你的答案,但我的任务是这样做的这个模板: class Vector { private: int _capacity; int _size; int _resizeFactor; int * _elements; – arik

+1

@arik那么你必须实现自己的引用计数。基本上只是在解构器中复制和减少计数时才增加计数。请记住使用原子或互斥体来避免多线程情况下的问题。据我所知,不能使用引用计数来实现浅拷贝。 – Null

+0

也可以使用'std :: vector'来完成许多你想要在你自己的'Vector'中做的事情。 – Phil1970