Archived

This topic is now archived and is closed to further replies.

Destructor and dangling pointer???

This topic is 5112 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This simple class dynamically allocates a float to a member float pointer. The destructor deletes the float and resets the pointer. class MyClass { public: MyClass(); MyClass(const MyClass& myclass); ~MyClass(); float myFloat; float *myFloatPtr; }; MyClass::MyClass(): myFloat(0.0f) { myFloatPtr = new float; *myFloatPtr = 0.0f; } MyClass::~MyClass() { delete myFloatPtr; //delete the float myFloatPtr = 0; //reset the pointer } BUT what if the 2 final lines where reversed to: { myFloatPtr = 0; // Would this reset the pointer or ///////////////////// assign a zero to the float variable? delete myFloatPtr; // AND does one delete pointers or merely ///////////////////// reset them? } S

Share this post


Link to post
Share on other sites
You''d leak memory in the second case. You''d be setting the pointer to 0, not the value of the float. Delete on 0 is valid, but does nothing.

You should delete anything you new, like your first case.

There is no *need* to set the pointer to 0 after the delete. In the destructor, it''s pointless. In other code though, it''s often done to ensure that:

1. If you attempt to use the pointer after the delete, you''ll be accessing invalid memory, the CPU will detect that, throw an exception, and the debugger will kick in... where you can see your fault and fix it.

2. If you delete it a second time, you''re deleteing 0, which does nothing.

3. It acts as a bool indicating whether the pointer is valid. When set to 0, you assume the pointer is invalid and take appropriate action (allocate something, take a different code path, etc).

Because code gets more and more complex, it''s best to get into the habit of writing 0 over a pointer after delete, to ensure all of the above. So while I say it''s pointless in your destructor, it doesn''t really hurt anything, or take very long... It''s still better to do it by habit than to lose the habit and miss doing it somewhere else.

Share this post


Link to post
Share on other sites
quote:
Original post by pinacolada
PS- Dynamically allocating a float is just silly. I hope you are only doing that as an exercise.


Yeah, seriously. A float is 4 bytes and a pointer is four bytes... Somethign wrong in that picture.

Share this post


Link to post
Share on other sites