Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete pointer object in C++

I read the following code for deleting pointer object in the open source project X3C.

//! Delete pointer object.
/*!
    \ingroup _GROUP_UTILFUNC
    \param p pointer object created using 'new'.
*/
template<class T>
void SafeDelete(T*& p)
{
    if (p != NULL)
        delete p;
    p = NULL;
    *(&p) = NULL;
}

But I don't know the meaning of this line:

*(&p) = NULL;

In the above line(p = NULL;), p is assigned to NULL. I think it needs to do that again in another way.

like image 316
thinkhy Avatar asked Jul 18 '11 04:07

thinkhy


1 Answers

It's completely pointless. Under ordinary conditions, the unary * and & operators are inverses of each other (with a few details, like that the expression &*foo is not an lvalue even if foo is an lvalue), although operator overloading can change that behavior.

However, since T* is always a pointer type regardless of the type T, it's impossible to overload the unary operator& for T*, so *(&p) is equivalent to just p, and assigning NULL to p a second time is useless.

like image 57
Adam Rosenfield Avatar answered Nov 10 '22 01:11

Adam Rosenfield