Setting Pointers to NULL in a Destructor
In object-oriented programming, it's common to allocate memory dynamically and release it using destructors. Consider the following class that allocates memory for an object of type Bar:
<code class="cpp">class Foo { public: Foo() : bar(new Bar) { } ~Foo() { delete bar; } void doSomething() { bar->doSomething(); } private: Bar* bar; };</code>
The question arises: is it beneficial to set the bar pointer to NULL in the destructor?
Argument against Setting to NULL
Contrary to popular belief, setting pointers to NULL in the destructor is not recommended. While it may seem like a good idea for debugging purposes, it could potentially lead to hidden problems in release builds.
If the pointer is set to NULL, a dangling reference to the deleted object might exist somewhere. In a debug build, this reference would be detected and trigger a diagnosable crash. However, in a release build, the buggy code might avoid using the pointer because it notices that it's NULL, thus obscuring the underlying issue.
Alternative Approach
Instead of setting the pointer to NULL, a better practice is to set it to a known bad pointer value. This way, any dangling references to the deleted object will still attempt to use the pointer, triggering a crash that can be more easily diagnosed and fixed.
For example, the following idiom could be used:
<code class="cpp">~Foo() { delete bar; if (DEBUG) bar = (bar_type*)(long_ptr)(0xDEADBEEF); }</code>
This approach allows potential bugs to be caught in debug builds while still ensuring that release builds detect and crash on dangling references.
Conclusion
While it might seem like a good idea to set pointers to NULL in destructors, doing so can hide potential issues in release builds. Instead, it's recommended to set pointers to a known bad value in debugging mode to facilitate diagnosis and debugging.
The above is the detailed content of Should Pointers Be Set to NULL in Destructors? A Look at Best Practices and Debugging.. For more information, please follow other related articles on the PHP Chinese website!