Assume a pointer object is being allocated on one point and it is being returned to different nested functions. At one point, I want to de-allocate this pointer after checking whether it is valid or already de-allocated by someone.
Is there any guarantee that any of these will work?
if(ptr != NULL)
delete ptr;
OR
if(ptr)
delete ptr;
This code does not work. It always gives Segmentation Fault
#include <iostream>
class A
{
public:
int x;
A(int a){ x=a;}
~A()
{
if(this || this != NULL)
delete this;
}
};
int main()
{
A *a = new A(3);
delete a;
a=NULL;
}
EDIT
Whenever we talk about pointers, people start asking, why not use Smart Pointers.
Just because smart pointers are there, everyone cannot use it.
We may be working on systems which use old style pointers. We cannot convert all of them to smart pointers, one fine day.
The two are actually equivalent, and also the same as
delete ptr;, because callingdeleteon aNULLpointer is guaranteed to work (as in, it does nothing).And they are not guaranteed to work if
ptris a dangling pointer.Meaning:
In your specific code, you get the exception because you call
delete thisin the destructor, which in turn calls the destructor again. Sincethisis neverNULL, you’ll get a STACK OVERFLOW because the destructor will go uncontrollably recursive.