Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!utgpu!water!watnot!watmath!clyde!rutgers!princeton!allegra!alice!bs From: bs@alice.UUCP Newsgroups: comp.lang.c++ Subject: Re: The supplied vector.h and operator= function. Message-ID: <6786@alice.uUCp> Date: Tue, 7-Apr-87 21:30:27 EST Article-I.D.: alice.6786 Posted: Tue Apr 7 21:30:27 1987 Date-Received: Sat, 11-Apr-87 07:57:03 EST References: <4509@columbia.UUCP> Organization: AT&T Bell Laboratories, Murray Hill NJ Lines: 39 Summary: delete[i] (beshers @ Columbia University CS Department) writes: > I've been perusing the files supplied with C++ v1.2 and have come > across something I don't understand. > > vector(type)& vector(type)::operator=(vector(type)& a) > { > register i = a.sz; ... > // ??????????????? > delete[i] v; > // ??????????????? ... > } > > I thought I understood everything until I got to the delete call > that I have marked off. In the immortal words of Cindy Lou Who, > "Why Santy Claus, why?"S > > It seems to me there are exactly two objects in this operation, > namely 'a' and 'this', both of which should have been initialized. > At least they *can* have been initialized, as in the code below. > Therefore each has some storage allocated for the array v. The > purpose of the assignment is to copy the contents of a->v onto > this->v, isn't it? Why, after we go to the trouble of copying this, > do we then delete it? The short answer is look at pages 92 and 259 in the C++ book (where the index directs you to). The longer answer is that a pointer type doesn't allow the compiler to determine whether you point to an object or an array of objects. This typically doesn't matter since the free store ``knows''. However, the free store doesn't know about destructors, so consider a vector(T) where T::~T() has been declared. Then, when we delete a vector(T) with 10 elements the destructor T::~T() needs to be called 10 times - once for each element. ``The system'' is too dump to know, so you must tell it, hence the ``spurious'' [i] in the example.