So, code as shown below. I've been implementing a very simple HashMap, HashEntry class is also defined simply.
Now I'm not super experienced with C++, but lets say new, delete and malloc/free/realloc/etc all cause my system to crash and the code needs to be adapted. I'm really not sure how to handle the constructor and deconstructor without those tools.
I know with some things, a string for example I can initialize like this: string program(sizeVariable)
, but I don't really see how to do that with this line table = new HashEntry*[TABLE_SIZE];
And then also lost as to handle the loss of delete in the deconstruction.
Any answers or advice appreciated, also forgive the formatting it doesn't look that ugly in my IDE.
class HashMap {
private:
HashEntry **table;
public:
HashMap()
{
table = new HashEntry*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
}
...
~HashMap()
{
for (int i = 0; i < tableSize; i++)
if (table[i] != NULL)
delete table[i];
delete[] table;
}
}
new, delete and malloc/free/realloc/etc all
You should almost never use any of those in C++. Manual memory management is pretty much dead for day-to-day C++ development. There are many better alternatives:
Smart pointers such as unique_ptr
and shared_ptr
.
Containers such as std::vector
or std::array
.
You need to read a good Modern C++ introductory book. Start with "A Tour of C++".
If you are doing manual resource management (...why?), you also want to follow the rule of five.