我已经开发了一个基于数组的哈希表实现,包含几个股票名称,符号,价格等。我需要从我的阵列中删除一个股票。我被告知使用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