Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!columbia!sylvester.columbia.edu!beshers From: beshers@sylvester.columbia.edu (Clifford Beshers) Newsgroups: comp.lang.c++ Subject: The supplied vector.h and operator= function. Message-ID: <4509@columbia.UUCP> Date: Wed, 1-Apr-87 12:04:08 EST Article-I.D.: columbia.4509 Posted: Wed Apr 1 12:04:08 1987 Date-Received: Sun, 5-Apr-87 05:17:29 EST Sender: nobody@columbia.UUCP Reply-To: beshers@sylvester.columbia.edu.UUCP (Clifford Beshers) Organization: Columbia University CS Department Lines: 95 Summary: Expires: Sender: Followup-To: Distribution: Keywords: I've been perusing the files supplied with C++ v1.2 and have come across something I don't understand. In the file vector.h, there is an assignment operator defined like this: class vector(type) { type* v; int sz; public: //... vector(type)& operator=(vector(type)&); //... }; vector(type)& vector(type)::operator=(vector(type)& a) { register i = a.sz; if (i != sz) callerror(vector,type,3,"different vector sizes in assignment"); register type* vv = &v[i]; register type* av = &a.v[i]; while (i--) *--vv = *--av; // ??????????????? delete[i] v; // ??????????????? return *this; } 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?" 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? I could understand this if there was a new copy of v created, but the only new variables are the walking pointers. I thought this code would remove one of two v's, leaving only one for two objects. I tried this out with the following code and it worked; I looked at the C code produced and it seemed to say the same thing. What's going on? /******* Code follows. *********/ #include #include #define FLOAT float declare(vector,FLOAT) implement(vector,FLOAT) ostream& operator<<(ostream& s, vector(FLOAT) v) { register int sz = v.size(); s << "("; for (int i=0; i < sz-1; i++) s << v.elem(i) << ","; return s << v.elem(sz-1) << ")"; } main() { int i; vector(FLOAT) fred(5); vector(FLOAT) bob(5); for (i=0; i