Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!att!ulysses!andante!alice!shopiro From: shopiro@alice.UUCP (Jonathan Shopiro) Newsgroups: comp.lang.c++ Subject: Re: deallocating an array of objects Message-ID: <9500@alice.UUCP> Date: 16 Jun 89 21:05:45 GMT References: <1245@cadillac.CAD.MCC.COM> Organization: AT&T Bell Laboratories, Murray Hill NJ Lines: 49 In article <1245@cadillac.CAD.MCC.COM>, rpj@redcloud.cad.mcc.com (Rich Johns) writes: - - Assume: - - class Foo { - Foo() { /*stuff*/} - ~Foo() { /* stuff*/} - }; - - main() { - Foo** fooArray = 0; - fooArray = new Foo*[100]; // fooArray points to 100 uninitialized pointers - - // do something - - } - - My question has to do with deallocating fooArray. If I am not concerned with - deleting the contents of fooArray (the 100 Foos), it seems like: Your problem is fooArray does not contain 100 Foos, it contains 100 pointers to Foo. - - delete fooArray; This works if the delete mechanism doesn't need to know how the size of the object being deleted. (Universally true, I believe). - - is correct. If I did want to delete the 100 Foos, would this be correct: - - delete [100]fooArray; This works too, but it doesn't delete the pointed-to Foos. - - or would I have to: - - for (int i = 0; i < 100; i++) { - delete fooArray[i]; - } This deletes the pointed-to Foos (and they better be there to delete) - delete fooArray; This deletes the array of pointers. Use the more explicit ``delete [100] fooArray'' as a good habit. - - Would the answer be different if Foo does not have a - constructor and destructor? no. -- Jonathan Shopiro AT&T Bell Laboratories, Warren, NJ 07060-0908 research!shopiro (201) 580-4229