Reputation: 925
class A {
struct structA;
}
Somewhere else:
structA* structAPointer = new structA;
A land far far away:
void Wonderland::rabbitHole(structA* structAPointer) {
delete structAPointer;
}
Does the delete operator free up the original memory allocated in 'Somewhere else'?
Upvotes: 3
Views: 175
Reputation: 76240
Does the delete operator free up the original memory allocated in 'Somewhere else'?
Yes, if the original structAPointer
has never been modified and is being passed to rabbitHole
.
The delete
operator works on the value (address) of the variable that holds the pointer so there's really anything stopping you to use rabbitHole
on any structA*
you have dinamically allocated.
It is to say, though, that using new
and delete
(or new[]
and delete[]
for that matter) is highly discouraged by the C++ community. There are a lot of alternatives to handle dynamically allocated memory that are proven to work better. For example the std
library holds a very good set of utilities to help you manage dynamic memory without the cons of handling the pointers yourself.
Upvotes: 0
Reputation: 952
Doesn't matter what part of the code allocated it delete will delete
anything created by new
while delete []
is for things created by new []
.
However usually you want the part that created it to be responsible for deleting it , to make managing memory easier.
Upvotes: 6