Re: when does the memory get officially released?
Jianwei Sun wrote:
I have a question, it may sound stupid. In c#/Java , when you create an object
on the heap and don't reference anymore, the memory will be cleared out when
garbage collection walk thourough the memory region.
What do you mean by "cleared out"?
But in C++, if I do:
Object* pObj=new Object();
Loosely speaking, the above allocates memory for an instance of Object,
and then constructs the instance in that memory. pObj is set to the
address of the memory that was allocated.
delete pObj;
This will call ~Object() for the object located at the address stored in
pObj. Then, it's likely that the memory will be returned to some
available pool at this point, where it might be returned by another new.
Then will the memory be cleared right away? Or when we do delete pObj, it
actually *just* break the reference to the object in the heap, so it will
be ready to be cleared. Thanks.
I suspect this is more correct, but I'm still not sure what you mean by
cleared. I think it's possible that memory isn't "cleared" depending on
what you mean.
If I do this:
Object* pObj=new Object();
Creates an instance of Object and sets pObj to point to this instance.
Object** ppObj=new Object*;
Create an uninitialized pointer to Object and set ppObj to point to this
pointer.
*ppObj=pObj;
Now ppObj points to a pointer to the object pointed to by pObj.
delete ppObj;
Delete the pointer to the pointer to Object that we just initialized.
But this doesn't delete the instance of Object that pObj still points to.
The object will still be availble after delete, right?
It will be, because you haven't deleted the instance of Object that pObj
still points to.
Your snippet, as it stands has a memory leak.
If you change the last line to:
delete *ppObj;
the instance of Object pointed to by pObj will be destroyed.
Might I suggest that you try this with this class:
class Object {
public:
Object() {
std::cout << "Object()" << std::endl;
}
~Object() {
std::cout << "~Object()" << std::endl;
}
};
Also, consider that if I run this little program,
struct Object {};
int main() {
Object *a = new Object();
Object *p1 = a;
delete a;
Object *b = new Object;
Object *p2 = b;
delete b;
const bool t = (p1 == p2);
}
The value of t is true before the program finishes. Of course, that
might change at the next run, but it is possible that during some runs t
will be true.
LR