Randen Davis
Randen Davis

Reputation: 11

Will deleting an object set its references equal to NULL?

I have an array of pointers to pointers, and when I do array [index]=classpointer; and call delete classpointer;, will the value stored at array[index] become NULL?

Upvotes: 1

Views: 656

Answers (4)

Ben Voigt
Ben Voigt

Reputation: 283893

Only if it's a std::weak_ptr. Normal pointers will remain unchanged.

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106246

To help you remember the answer to this, consider:

T* p = ...;
delete p;

What happens to p afterward the delete and before it itself leaves scope, or the object it's member data for is destroyed? There is no single answer. So, if C++ took the additional action to set p to NULL, then at least some of the time it would wasted effort - setting a variable that was discarded immediately afterwards. In C++, a guiding principle is that there aren't runtime costs for features you may not want or need.

Further, consider:

T* p = ...
T* p1 = p;
delete p;

Suddenly the idea of having p set to NULL - which may have seemed to make it easy to check pointers for validity - falls over. It's just not practical for the compiler to know every other pointer that might still refer to the just-deleted object, and the cost of tracking that information at run-time and NULLing all the pointers is impractical.

So, to be really explicit, if in...

T* p = ...;
delete p;

...p was set to 0x12345678, then after the delete p will still be 0x12345678. delete never changes its argument. Any attempt to access the memory at that address will result in undefined behaviour (unless of course the same address happens to be returned by a subsequent heap allocation request).

Separately, if you do set a pointer to NULL yourself, you can safely call delete on it again, so there's never any point in doing this:

if (p != NULL) delete p;

Upvotes: 2

Tom Shaw
Tom Shaw

Reputation: 660

No. An array index is always an integer (unless you're doing some crazy operator overloading). Integers are primitive datatypes and it doesn't make sense for a primitive to be NULL.

Did you mean, "Will array[index] become NULL?" See @Mahesh's answer.

Upvotes: 4

Mahesh
Mahesh

Reputation: 34655

No. It still remains pointing to the location classpointer was earlier pointing to or in other words, it goes dangling.

Upvotes: 6

Related Questions