+ Reply to Thread
Results 1 to 5 of 5
  1. #1
    Junior Member
    Join Date
    Feb 2002
    Posts
    20

    C++ distructor question

    When i create a new socket object, the value in the point to the object is not NULL
    if (IncomingSocket == NULL) IncomingSocket = new Socket;
    This way I dont have any memory leaks, etc
    Now when I need to destroy the socket...
    if (IncomingSocket != NULL) delete IncomingSocket;
    This way i dont try to delete a NULL object and avoid a memory fault.
    The problem is that I must set the point = NULL;
    IncomgingSocket=NULL;
    This is a pain when I have in a multithreaded app when sycronization can realy ruin my day.
    It would be nice if in the destructor, I could set that pointer value to null before returning.
    // ------------------------------------------------------------------
    Socket::~Socket()
    {
    if (iSock > -1) closesocket(iSock);

    if (szPeerName) delete [] szPeerName;
    //*** Somehow set the point = NULL;
    }
    Anyone know how to do this? Only trick I can think of gets realy nasty with stack calls.
    tony

  2. #2
    Member SpiffGQ's Avatar
    Join Date
    Oct 2001
    Location
    United States
    Posts
    408
    Why would you need to set the pointer to NULL? Isn't that kind of the point of delete?

  3. #3
    Ultimate Member FalcomPSX's Avatar
    Join Date
    Oct 2001
    Location
    SoCal.
    Posts
    2,855
    not really t048, the delete keyword deallocates the memory allocated with new. just setting the pointer to NULL leaves the memory allocated. though i'm not sure how to accomplish what wants...
    Last edited by FalcomPSX; March 30th, 2002 at 03:54 AM.
    FalcomPSX

  4. #4
    Member SpiffGQ's Avatar
    Join Date
    Oct 2001
    Location
    United States
    Posts
    408
    What would this accomplish?

  5. #5
    Member
    Join Date
    Feb 2002
    Posts
    161
    If you don't set the pointer to NULL, and you attempt to use it again, your program will most likely do strange things, as the memory it points to is no longer guaranteed to be valid. Also, if you try to delete it again without setting it to NULL, your program will most likely die a horrible death. Pointers should almost always be set to NULL after they have been deleted.

    TonyM123: Although it's not an elegant solution, you could always take advantage of the preprocessor. Something like:
    #define SafeDelete(p) { delete p; p = NULL; }

    I don't think there is a good way of doing what you are looking for.

Quick Reply Quick Reply

If you are already a member, please login above.

What is the color of the sky?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may post new threads
  • You may post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Copyright 2014 All Enthusiast, Inc