Thread: New and delete question

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    2

    New and delete question

    Hello,

    I am a some what new C++ guy, and I am looking at someone else's code and this method of newing and deleting seems odd to me.

    Is there anything wrong with this method of deleting?

    first new an object:

    Code:
    Object *pObject = new Object;
    Later when the object is deleted:

    Code:
    if (pObject != NULL)
    {
       Object *pTemp = pObject;
       pObject = NULL;
       delete pTemp;
    }
    It seems to me that they are just deleting the pointer to pObject, and not actually reclaiming the memory. I am wondering why not just delete pObject, and then null Pobject pointer?

    Any help would be much appreciated!

    Thanks

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    pTemp is unnecessary here. Also the NULL check is unnecessary, because it is OK to attempt to delete NULL pointers (delete checks itself).

    Code:
    Object* p = new Object;
    //...
    delete p;
    p = NULL;  //if you feel it is necessary: most often p would go out of scope anyway
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Registered User
    Join Date
    Oct 2009
    Posts
    2
    Ok, thanks for the reply.

    My main question is, does the opening post code cause a memory leak? Or is it just unnecessary?

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    No leak in the first code.

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    The if statement is unnecessary, but without knowing the context from which this code comes from, pTemp may be very necessary! In COM for example, the final release must be done like this in order to prevent re-entrancy issues, e.g. where an object's destructor happens to increase and then decrease its own refcount, which can happen for valid reasons, and this "trick" then prevents double-deletion.

    Therefore nobody can yet say with absolute certainty that this "trick" isn't necessary here. We would have to see more code. I would say that it's "quite likely" to be unnecessary here, but the sheer fact that someone has chosen to use it gives a good chance that there was a valid reason for it.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed