home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!taumet!steve
- From: steve@taumet.com (Steve Clamage)
- Subject: Re: can I 'delete' without a 'new'?
- Message-ID: <1992Sep5.160932.19698@taumet.com>
- Organization: TauMetric Corporation
- References: <1992Sep4.171020.4762@kentrox.uucp>
- Date: Sat, 5 Sep 1992 16:09:32 GMT
- Lines: 44
-
- peter@kentrox.uucp (Peter Uchytil) writes:
-
- >I can't seem to find any references which indicate whether I can do this
- >or not...
-
- The ARM is very explicit on this point, and so should be any C++ text.
-
- You may use 'delete' only with a pointer obtained from 'new', or with
- the value zero. Array syntax must be used with delete if and only if
- array syntax was used with the corresonding new. You may delete the
- pointer at most once.
-
- The results of any other usage are undefined. Here are two ways to
- handle the problem of not knowing when to delete a pointer.
-
- 1. If you don't know whether the space, even if allocated, should be
- deleted, use a flag:
- class X {
- char* data;
- int do_del;
- public:
- X() { data = 0; do_del = 0; }
- X(int s) { data = new char[s]; do_del = 1; }
- X(char* p) { data = p; do_del = 0; }
- ~X() { if( do_del ) delete [] data; }
- char* get_data() { do_del = 0; return data; }
- };
- The last function returns a pointer to an internal data structure, so
- we don't want to delete the data automatically.
-
- 2. If the space might not have been allocated, but if so must always be
- deleted, initialize the pointer to zero. It is always harmless to
- delete a null pointer.
- class X {
- char* data;
- public:
- X() { data = 0; } // delete will be harmless
- X(int s) { data = new char[s]; }
- ~X() { delete [] data; }
- };
- --
-
- Steve Clamage, TauMetric Corp, steve@taumet.com
- Vice Chair, ANSI C++ Committee, X3J16
-