views:

82

answers:

1

In Visual Studio 2008 (C++) I have a class destructor (Let's call this class 'A') which deletes a pointer to a different class (Let's call this class 'B').

it looks like this:

A::~A()
{
    delete B;
    B = NULL;
}

My B class has a pointer to the instance of A that created it. In B's destructor, I delete everything in B, except for the pointer to the instance of A.

In my debug build, it works okay, but fails on my release build..

In the debug build, right after B is deleted but before B is reassigned to NULL, The value of the pointer to the instance of A is something weird like 0xdddddddd.. However in the Release build, it is still pointing to the instance of A.. In both cases the pointer to B is still valid and B is not destroyed. What is going on and how do I fix it?

A: 

If I understand what you are saying, everything is working perfectly fine. After the call to delete B, the pointer held by variable B will be unchanged. It will still contain the address of the memory. The memory may or may not change; that part is completely undefined and depends on other things happening in the system at the moment and what the heap manager does.

After the delete to B is completed (and B's destructor has run), the memory in which B was stored may or may not be changed (again it depends on the heap manager). So the fact that B's pointer to A is changed in one build type and not the other is fine. After the delete, you cannot use anything in B.

Mark Wilkins
Thanks for the reply.. You say that after I delete the instance of B, I cannot use anything in that deleted instance.. But what happens to the pointer to the instance of A? That instance of A would lose a pointer that was pointing to it, but it doesn't matter cause it should be deleted when A's destructor is called right? For some reason my app is wonky in the Release build scenario =/
krebstar
A pointer in C++ is simply a memory address. As long as object A is valid, then that address is valid. There is no reference counting in this situation (as described), so the existence of a pointer to A has no affect on whether A is valid or not. The fact is that after B has been deleted, the memory that made up object B cannot be used reliably.
Mark Wilkins