home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!cs.utexas.edu!sun-barr!olivea!spool.mu.edu!wupost!waikato.ac.nz!comp.vuw.ac.nz!newshost!srlncnc
- From: srlncnc@gopher.dosli.govt.nz (Chris Crook)
- Newsgroups: comp.lang.c++
- Subject: Using delete with arrays - help please!
- Message-ID: <1992Nov16.023852.24205@gopher.dosli.govt.nz>
- Date: 16 Nov 92 02:38:52 GMT
- Sender: srlncnc@gopher.dosli.govt.nz (Chris Crook)
- Organization: Department of Survey and Land Information, New Zealand
- Lines: 76
-
- Hi
-
- Can you clear up a bit of confusion I have about the use of delete with
- arrays.
-
- My understanding is that I can allocate an array of class instances using
- the syntax
-
- MyClass arrayOfInstances = new MyClass[arraySize];
-
- and that when I want to delete it I use
-
- delete [] arrayOfInstances
-
- I have written a small test program to let me know when the constructors
- and destructors are called, and this all seems to work. If I omit the
- [] in the delete statement then the destructor is called only once. It
- also leads to a "Null pointer assignment" error from Borland C++ when the
- program ends, presumably because the memory allocation has got messed
- up.
-
- What I am puzzled about is the wide use of arrays of characters in
- the Borland code examples in which the arrays are allocated as
-
- char *aBuffer = new char[bufferSize];
-
- delete aBuffer;
-
- Can you tell me why this works? Why doesn't it need the [] after the
- delete operator? Is it because char is an internal type?
-
-
- My apologies if this is an obvious question - I am still waiting for our
- library to get the C++ programming manual, so I do not have a definitive
- C++ reference available.
-
- Thanks in advance for any help
-
- Chris Crook
-
- P.S: below is the test program I was working with
- =====================================================================
-
- // Just testing constructors and destructors on an array
-
- #include <iostream.h>
-
-
- class MyClass {
- int instance; // Number of current instance
- static int count; // counter of instances created
- public:
- MyClass(); // Default constructor and destructor
- ~MyClass();
- };
-
- int MyClass::count = 0;
-
- MyClass::MyClass() {
- instance = ++count;
- cout << "MyClass instance " << instance << " created\n";
- }
-
- MyClass::~MyClass() {
- cout << "MyClass instance " << instance << " deleted\n";
- }
-
- // Test program includes both automatic and dynamic allocation.
-
- int main( int argc, char *argv[] ) {
- MyClass oneArray[5];
- MyClass *anArray = new MyClass[6];
- // delete [] anArray;
- delete anArray;
- return 0;
- }
-