I have the following class:
class Stack {
struct Link {
void* data;
Link* next;
void initialize(void* dat, Link* nxt);
}* head;
public:
void initialize();
void push(void* dat);
void* peek();
void* pop();
void cleanup();
};
The pop method is:
void* Stack::pop() {
if(head == 0) return 0;
void* result = head->data;
Link* oldHead = head;
head = head->next;
delete oldHead;
return result;
}
oldHead is a pointer to a struct Link, which has a void pointer as member. So by deleting oldHead I’m implicitly deleting that void pointer, right?
I’m reading Thinking in C++ by Bruce Eckel, and it says that deleting void pointers doesn’t clean things up properly because delete needs to know the type of the pointer.
This code is implicitly deleting the void pointer data, so: Can someone explain why is this (implicit) way of deleting a void pointer different from deleting with delete <void pointer>?
Your terminology is causing ambiguity, but let me explain. Let’s say you have:
Whenever a
fooends its lifetime,barsimply stops existing too. So if you have:You’ve leaked, as
new intis never deleted. Likewise, when you do:You’ve still leaked, since when
delete fis run, you simply end the lifetime of whatfis pointing to (just like what happened automatically above), ergobarsimply ceases to exist and thenew intis not deleted.To summarize, when an object’s lifetimes ends,
deleteis not called on the members that are a pointer.So when you call delete on a
Link, it’s the same situation asbarinfooabove: you’re deleteing the memory for aLinkcausingdatato stop existing, but not actually deleting what it’s pointing at.