Delete pointer object in C++
Asked Answered
O

1

7

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.

Oculomotor answered 18/7, 2011 at 4:29 Comment(8)
That's interesting. I wonder why in the world they did that. Maybe for compiler optimisation reasons or something.Kronick
They don't do that *(&x) = NULL; thing for SafeDeleteArray weirdly.Kronick
People write weird code for all sorts of superstitious reasons. Or perhaps some compiler they were using had a bug?Travancore
@Seth Carnegie : I also think this line of code is weirdly:) And I want to find the reason for that.Oculomotor
@Oculomotor I think we've all agreed that it's retarded pointlessness. Refer to Adam's answer below.Kronick
@Greg Hewgill: These code were originally compiled in the Windows 32 bit platform using Visual Studio 2005 and Visual Studio 2008.Oculomotor
See #541420 for a simple counter-example why this is pointlessEdgaredgard
@MSalters: Thax! Posts in that question are very detailed.Oculomotor
R
12

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.

Rothberg answered 18/7, 2011 at 4:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.