Thread: Delete query

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    1

    Delete query

    Hi all,

    I know there are a lot of questions about delete and delete[] but I can't seem to get a straight answer to this.

    I create a bunch of objects, lets call them Things:

    Thing* thing1 = new Thing();
    ...
    Thing* thing10 = new Thing();

    I then create an array of pointers to these things:

    Thing** myArray = new Thing*[10];

    And then copy the pointers across:

    myArray[0] = thing1;
    ...
    myArray[9] = thing10;

    Now, if I want to properly clean up "myArray" I assume I call:

    delete[] myArray;

    But what does this destroy? Is it just the list of pointers or does it destroy all the objects in it too?

    i.e. are all the thing1... thing10 pointers still valid after the delete[] call?

    Thanks, Gords

  2. #2
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,130
    Easy answer is this:

    Anything created with "x = new Thingy;" must be destroyed by "delete x";
    Anything created with "x = new Thingy[y];" must be destroyed by "delete [] x;"

    There is no cascading or recursive delete.

    In you example you must do both. Use a loop and "delete" each pointer by hand, then call "delete []" on your array.
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Of course, in C++ you should probably be using classes that encapsulate the memory management and do the deletion for you, like perhaps a vector of shared_ptr's.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Delete Function in Doubly Linked List
    By Dampecram in forum C Programming
    Replies: 5
    Last Post: 11-15-2008, 04:30 PM
  2. BST delete again, but this time I think I'm close
    By tms43 in forum C++ Programming
    Replies: 9
    Last Post: 11-05-2006, 06:24 PM
  3. delete and delete []
    By Lionel in forum C++ Programming
    Replies: 8
    Last Post: 05-19-2005, 01:52 PM
  4. why is this prog crashing on delete?
    By Waldo2k2 in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2002, 11:17 PM
  5. Problem need help
    By Srpurdy in forum C++ Programming
    Replies: 1
    Last Post: 07-24-2002, 12:45 PM