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

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!kentrox!peter
  3. From: peter@kentrox.uucp (Peter Uchytil)
  4. Subject: can I 'delete' without a 'new'?
  5. Message-ID: <1992Sep4.171020.4762@kentrox.uucp>
  6. Organization: ADC Kentrox, Portland OR
  7. Date: Fri, 4 Sep 1992 17:10:20 GMT
  8. Lines: 54
  9.  
  10. I can't seem to find any references which indicate whether I can do this
  11. or not, so I'm appealing to the net.wisdom.  Here's what I've got:
  12.  
  13. class foo {
  14.   char *String;
  15. public:
  16.   foo();
  17.   foo( char * );
  18.   ~foo();
  19.   void set( char * );
  20. };
  21.  
  22. foo:foo() { };
  23.  
  24. foo:foo( char *inString ) {
  25.   String = new char[strlen( inString )];
  26.   strcpy( String, inString );
  27. }
  28.  
  29. void foo:set( char *inString ) {
  30.   String = new char[strlen( inString )];
  31.   strcpy( String, inString );
  32. }
  33.  
  34. foo:~foo() {
  35.   delete [] String;
  36. }
  37.  
  38. The question is what will happen if I create a foo with the empty constructor
  39. and never call 'set'?  Since 'new' has never been called, what will 'delete'
  40. try to delete?  Looks like a real good way to frazzle the system.  Yes?  No?
  41.  
  42. The reason I want to do this is I want to declare an array of 'foo'.  To do
  43. the assignment:
  44.        LotsaFoos foo[100]; 
  45. I have to use an empty constructor.  
  46.  
  47. One idea I had was to have the empty constructor do something like:
  48.        String = new char[1];
  49.  
  50. But then does 'set' first have to do a 'delete' before doing another 'new'?
  51. I would assume it does.
  52.  
  53. Summary of questions:
  54.       1) What happens if I call 'delete' without having called 'new'?  
  55.       2) What happens if I call 'new' twice in a row?  Sounds like I'm going
  56.          to make some memory become unrecoverable.  
  57.  
  58. Thanks for any comments!
  59.  
  60. Pete
  61. -- 
  62. Peter Uchytil   | ADC Kentrox Industries | "They say that I'm a dreamer
  63. peter@kentrox.com |  Portland, Oregon    |  And I tell them they are right"
  64.