Destructor and dangling pointer???

Started by
5 comments, last by dunkel3d 20 years, 4 months ago
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
Advertisement
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.
PS- Dynamically allocating a float is just silly. I hope you are only doing that as an exercise.
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.
Thank you for your responses. This is simply an example.

S
There''s something about a dangling pointer leaking that rings quite unhealthy...

[Hugo Ferreira][Positronic Dreams][Colibri 3D Engine][Entropy HL2 MOD][Yann L.][Enginuity]
Stop reading my signature and click it!

you should probably see a doctor about it

This topic is closed to new replies.

Advertisement