When I implement pop() and destructor of a stack which holds nodes,should I delete node->data before deleting the node itself or should I just delete the node and let the caller who creates node->data to delete the node->data? If letting the caller to do that, when and how should the caller deletes the data? Should it call in this way: {data = stack.top(); delete data; stack.pop();}?
I have not seen any code which delete node->data, neither in a implementation of pop() nor a caller function. That is why I am confused.
Here I copy the stack I implemented using link list.Please take a look at the note of pop() and ~stack() for my question. Thanks for your help.
typedef struct Node_t{
struct Node_t* next;
void* data;
}Node;
class stack {
public:
stack(): _head(null), _size(0){}
~stack();
void push(void* data);
void pop();
void* top();
bool empty();
stack(const stack& original);
stack& operator=(const stack& original);
private:
Node* _head;
int _size;
};
stack::~stack{
Node* next = null;
while(_head){
next = _head->next;
//should delete _head->_data???
delete _head;
_head = next;
}
_size = 0;
}
void stack::push(void* data){
Node* elem = new Node;
elem->data = data;
elem->next = _head;
_head = elem;
_size++;
}
void stack::pop(){
Node* next = NULL;
if (_head) {
next = _head->next;
//should delete _head->_data???
delete _head;
_head = next;
_size--;
}
}
void* stack::top() const{
if (_head) {
return _head->_data;
}
}
bool stack::empty(){
if(_size>0) return false;
else return true;
}