2017-11-11 45 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