我已經開發了一個基於數組的哈希表實現,包含幾個股票名稱,符號,價格等。我需要從我的陣列中刪除一個股票。我被告知使用delete操作符是不好的面向對象的設計。面向刪除的好的面向對象設計是什麼?C++中的安全刪除
bool hash::remove(char const * const symbol, stock &s,
int& symbolHash, int& hashIndex, int& usedIndex)
{
symbolHash = this->hashStr(symbol); // hash to try to reduce our search.
hashIndex = symbolHash % maxSize;
usedIndex = hashIndex;
if ( hashTable[hashIndex].symbol != NULL &&
strcmp(hashTable[hashIndex].symbol , symbol) == 0)
{
delete hashTable[hashIndex].symbol;
hashTable[hashIndex].symbol = NULL;
return true;
}
for (int myInt = 0; myInt < maxSize; myInt++)
{
++usedIndex %= maxSize;
if (hashTable[usedIndex].symbol != NULL &&
strcmp(hashTable[usedIndex].symbol , symbol) == 0)
{
delete hashTable[usedIndex].symbol;
hashTable[usedIndex].symbol = NULL;
return true;
}
}
return false;
}
注意到,我有一隻股票& S作爲參數,我可以這樣使用它:
s = &hashTable[usedIndex];
delete s.symbol;
s.symbol = NULL;
hashTable[usedIndex] = &s;
這樣確實可以但是,它會導致內存泄漏。即使如此,我不確定它是否是好的對象orinted設計。
這是我的標題,股票和所有的東西被初始化和定義。
//hash.h
private:
friend class stock;
int isAdded; // Will contain the added hash index.
// Test for empty tables.
// Can possibly make searches efficient.
stock *hashTable; // the hashtable will hold all the stocks in an array
};
//哈希表構造函數
hash::hash(int capacity) : isAdded(0),
hashTable(new stock[capacity]) // allocate array with a fixed size
{
if (capacity < 1) exit(-1);
maxSize = capacity;
// We can initialize our attributes for the stock
// to NULL, and test for that when searching.
for (int index = 0; index < maxSize; index++)
{
hashTable[index].name = NULL;
hashTable[index].sharePrice = NULL;
hashTable[index].symbol = NULL;
}
}
// stock.h
... 友元類的HashMap;
private:
const static int maxSize; // holds the capacity of the hash table minus one
date priceDate; // Object for the date class. Holds its attributes.
char *symbol;
char *name;
int sharePrice;
};
我的問題仍然只是,我如何執行安全刪除?
s = &hashTable[usedIndex];
delete s.symbol;
s.symbol = NULL;
hashTable[usedIndex] = &s;
這似乎工作,但導致內存泄漏!這是如何安全地完成的?
刪除hashTable [usedIndex] .symbol; hashTable [usedIndex] .symbol = NULL; < - 沒有這樣做。
數組中插槽的狀態(空等)不應記錄在庫存實例中。這是不好的面向對象的設計。相反,我需要將陣列插槽的狀態存儲在陣列插槽本身中。
我該怎麼做?
我不確定刪除操作符,但是有大量的const char *而不是字符串,並且重新設計輪子H^H^H而不是地圖是重要的設計。 – hirschhornsalz 2009-11-21 01:06:53
使用刪除與面向對象的設計無關,誰告訴你不知道他們在說什麼。如果你在堆上分配內存來刪除它,那麼這段時間。現在我們嘗試使用像RAII這樣的習語來封裝堆內存管理的過程,但是在某些時候,內存仍然需要被釋放。 – 2009-11-21 01:07:27
這裏沒有足夠的信息來回答這個問題。你設法傳達的唯一事實是:你有一個可以被錯誤使用的類,因爲你可以公開訪問你的結構的內部部分。這就是糟糕的OO設計。該類的用戶不需要知道或能夠操縱內部結構或修改將使其處於不一致狀態的實例。 – 2009-11-21 01:17:55