From: horst DOT kraemer AT snafu DOT de (Horst Kraemer) Newsgroups: comp.os.msdos.djgpp Subject: Re: "delete" and "delete []" operators Date: Sat, 11 Jul 1998 11:28:36 GMT Organization: Unlimited Surprise Systems, Berlin Lines: 109 Message-ID: <35a7423b.178710164@news.snafu.de> References: <199807092012 DOT QAA25515 AT delorie DOT com> <35a71a7e DOT 2075466 AT news DOT Austria DOT EU DOT net> NNTP-Posting-Host: n241-113.berlin.snafu.de To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk On Fri, 10 Jul 1998 14:36:25 GMT, sparhawk AT eunet DOT at (Gerhard Gruber) wrote: >> #include >> class Foo >> { >> public: >> ~Foo() { printf("~Foo!\n"); }; >> }; >> int main(void) >> { >> Foo *foo1 =3D new Foo[5]; >> Foo *foo2 =3D new Foo[5]; >> printf("delete foo1\n"); >> delete foo1; >> printf("delete [] foo2\n"); >> delete [] foo2; >> return 0; >> } >> >>In both cases, an array of objects is created. However, only in the >>delete [] case will all the destructors be called. >> >>The obscure part is that some compilers manage this by allocating an >>additional bit of memory to keep track of the number of objects in the >>array, and free this memory in delete []. If you call delete instead >>of delete[], that memory is never freed and you have a memory leak. >Does this mean that, in your above example, for each object in the array >is the constructor called by new[] and the destructor by delete[]?. Yes. By definition of the C++ language new classtype[10]; will allocate an array of 10 objects of type 'classtype' by calling the default ctor for every array element. If there is no accessible default ctor as in the example below you will get a syntax error. struct X { X(int) {} }; or struct X { protected: X() {} }; X* p = new X[10]; // error: Can't find default ctor delete [] p will call the dtor for _every_ array element. Check it with your compiler. Note that the rule p = new ... [n] <---> delete [] p p = new ... <---> delete p does not apply to the "textual look" of the call to the new operator but rather to its meaning. After class X; typedef X Xa[10]; X* p = new Xa; you have to delete p via 'delete [] p' (!). This a case where 'new xa' does _not_ return a pointer to the "type xa" but to the base type of the xa, i.e. the above statement is equivalent to X* p = new X[10]; If you want an "array of Xa", you may say Xa * xap = new Xa[100]; though. Typedefs for arrays are a case where new Xa; and new Xa[n]; are _not_ returning the same pointer type, the first means new X[10]; the latter means new X[n][10]; // ! while 'new X' and 'new X[10]' will both return a 'pointer to X'. Typedefs are weird, aren't they ? ;-) Regards Horst