Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!mips!sgi!shinobu!odin!sgihub!dragon!xanadu.wpd.sgi.com!pal From: pal@xanadu.wpd.sgi.com (Anil Pal) Newsgroups: comp.lang.c++ Subject: Re: new/dispose behavior Message-ID: <1991Apr30.231252.26736@dragon.wpd.sgi.com> Date: 30 Apr 91 23:12:52 GMT References: <1619@msa3b.UUCP> Sender: news@dragon.wpd.sgi.com (CNews Account) Reply-To: pal@wpd.sgi.com Organization: Silicon Graphics, Inc. Lines: 33 In article <1619@msa3b.UUCP>, kevin@msa3b.UUCP (Kevin P. Kleinfelter) writes: |> I'm reading along in a book about C++, and I see that one can do: |> |> char* s = new char [40]; |> delete s; |> |> int *p = new int [40]; |> delete 40 p; |> |> Either I'm confused or the book is! Actually, both of these examples are incorrect as of the latest draft of the C++ standard. The correct way (for both cases) is: mumble* x = new mumble[40]; delete [] x; Earlier implementations of C++ (for example, those based on cfront 2.0 or before) required the programmer to explicitly supply the count (40) in the delete. What happens if you forget and do a simple delete x; ? Well, for the examples quoted (int and char) usually nothing dramatic. The full storage will probably be returned to the free pool (in typical malloc/free based implementations). If the type mumble is a class with a destructor, however, forgetting the array form of the delete will result in a single destructor being called, for the 0-th element in the array. Using the array syntax (delete [] x;) will correctly call the destructor for all elements of the array. -- Anil A. Pal, Silicon Graphics, Inc. pal@wpd.sgi.com (415)-335-7279