Path: utzoo!utgpu!watserv1!watmath!att!dptg!ulysses!andante!alice!shopiro From: shopiro@alice.UUCP (Jonathan Shopiro) Newsgroups: comp.lang.c++ Subject: Re: An array of objects again! Message-ID: <10463@alice.UUCP> Date: 10 Feb 90 19:45:43 GMT References: <1990Feb9.201223.14332@sdr.slb.com> Organization: AT&T Bell Laboratories, Murray Hill NJ Lines: 49 In article <1990Feb9.201223.14332@sdr.slb.com>, saito@sdr.slb.com (Naoki Saito) writes: = Suppose I want to declare an array of object Cell. There are two ways to = declare this. = = (1) array of pointers to objects = Cell** ppc = new Cell*[N]; // null constructor. = for (int i = 0; i < N; i++) = ppc[i] = new Cell(i); // constructor with some argument. = = (2) array of objects = Cell* pc = new Cell[N]; // null constructor. = for (int i = 0; i < N; i++) = pc[i] = *(new Cell(i)); // constructor with some argument. This is surely not what you want to do. Each invocation of ``new Cell(i)'' creates an object on the free store that will never be deleted. Instead you can use a temp on the stack with the code pc[i] = Cell(i); // constructor with some argument. = = Now, the differences of these two approaches look like = o The approach (1) needs N x (sizeof(Cell*) + sizeof(Cell)) memory space = whereas (2) only needs N x sizeof(Cell). Also approach (1) costs you an extra indirection each time you reference an array element. = o The approach (2) creates temporary objects and calls assignment operator = = i.e., pc[i] = Cell(i); is equivalent to [corrected by JES] = Cell temp(i); = pc[i] = temp; // assignment operator. = ~temp(); = whereas (1) simply copies the address to the pointers. = What I would do in this case is the following (2.5) array of objects with re-constructor Cell* pc = new Cell[N]; // null constructor. for (int i = 0; i < N; i++) pc[i].re_init(i); // re-constructor with some argument. That is, I would be sure that the default (i.e., no-arg) constructor is empty, or as inexpensive as possible, and I would provide a member function, Cell::re_init() which would modify the product of the default constructor so that the result was what I originally intended. This may be less than elegant, but it works and is more efficient that either of the Naoki's suggestionns. Assignment operations can be expensive, and can often be avoided. -- Jonathan Shopiro AT&T Bell Laboratories, Warren, NJ 07060-0908 research!shopiro (201) 580-4229