c++ - Is clearing a vector considered a proper way of managing memory -
i tried make question title descriptive possible won't have click on question figure out whether have answer question.
i implementing chaining hash table
class assignment, , have come conclusion vector
best serve purpose of project.
consider following snippet of code:
struct node { public: node(string key, node * next = null) { this->key = key; this->next = next; } string key; node * next; }; class htable { private: static const int table_size = 100; vector <node*> table; public: htable() { table.resize(table_size); (int = 0; < table_size; i++) table[i] = null; } ~htable() { table.erase(table.begin(), table.begin() + table_size); } };
will erase
function in htable
class destructor
perform proper memory management?
will erase function in htable class destructor perform proper memory management?
no. vector<node*>
doesn't use smart pointers, nothing call destructors nor release memory objects in data structure.
doing delete
on each node*
(or use smart pointers) first step, wouldn't enough because node
destructor doesn't invoke destructor(s) linked node
s.
there's no need call erase
- vector
automatically invokes destructors elements contains when htable
object destructor runs - problem node*
elements don't trigger destruction actions, need explicit loop calling delete
or use smart pointers.
separately, have hash set rather map... there're key
s.
perhaps should try:
std:vector<std::list<std::string>>
this take care of data cleanup automatically.
Comments
Post a Comment