home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / cplus / 13333 < prev    next >
Encoding:
Text File  |  1992-09-07  |  1.7 KB  |  55 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!taumet!steve
  3. From: steve@taumet.com (Steve Clamage)
  4. Subject: Re: can I 'delete' without a 'new'?
  5. Message-ID: <1992Sep5.160932.19698@taumet.com>
  6. Organization: TauMetric Corporation
  7. References: <1992Sep4.171020.4762@kentrox.uucp>
  8. Date: Sat, 5 Sep 1992 16:09:32 GMT
  9. Lines: 44
  10.  
  11. peter@kentrox.uucp (Peter Uchytil) writes:
  12.  
  13. >I can't seem to find any references which indicate whether I can do this
  14. >or not...
  15.  
  16. The ARM is very explicit on this point, and so should be any C++ text.
  17.  
  18. You may use 'delete' only with a pointer obtained from 'new', or with
  19. the value zero.  Array syntax must be used with delete if and only if
  20. array syntax was used with the corresonding new.  You may delete the
  21. pointer at most once.
  22.  
  23. The results of any other usage are undefined.  Here are two ways to
  24. handle the problem of not knowing when to delete a pointer.
  25.  
  26. 1. If you don't know whether the space, even if allocated, should be
  27. deleted, use a flag:
  28.     class X {
  29.         char* data;
  30.         int do_del;
  31.     public:
  32.         X()        { data = 0; do_del = 0; }
  33.         X(int s)    { data = new char[s]; do_del = 1; }
  34.         X(char* p)    { data = p; do_del = 0; }
  35.         ~X()    { if( do_del ) delete [] data; }
  36.         char* get_data() { do_del = 0; return data; }
  37.     };
  38. The last function returns a pointer to an internal data structure, so
  39. we don't want to delete the data automatically.
  40.  
  41. 2. If the space might not have been allocated, but if so must always be
  42. deleted, initialize the pointer to zero.  It is always harmless to
  43. delete a null pointer.
  44.     class X {
  45.         char* data;
  46.     public:
  47.         X()        { data = 0; }    // delete will be harmless
  48.         X(int s)    { data = new char[s]; }
  49.         ~X()    { delete [] data; }
  50.     };
  51. -- 
  52.  
  53. Steve Clamage, TauMetric Corp, steve@taumet.com
  54. Vice Chair, ANSI C++ Committee, X3J16
  55.