home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / cplus / 13336 < prev    next >
Encoding:
Internet Message Format  |  1992-09-08  |  1.9 KB

  1. Path: sparky!uunet!igor!thor!rmartin
  2. From: rmartin@thor.Rational.COM (Bob Martin)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: can I 'delete' without a 'new'?
  5. Message-ID: <rmartin.715714307@thor>
  6. Date: 5 Sep 92 17:31:47 GMT
  7. References: <1992Sep4.171020.4762@kentrox.uucp>
  8. Sender: news@Rational.COM
  9. Lines: 55
  10.  
  11. peter@kentrox.uucp (Peter Uchytil) writes:
  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. It is, if the member variable String is non-zero.  But if your default
  43. constructor sets this variable to zero, then the 'delete' in the
  44. destructor will be safe.  Operator delete is well-behaved when passed
  45. a 0 argument.
  46.  
  47. |Summary of questions:
  48. |      1) What happens if I call 'delete' without having called 'new'?
  49.  
  50.  
  51. If the pointer is zero, then nothing bad happens.  If the pointer is
  52. non-zero then system frazzling is imminent.
  53.  
  54. |      2) What happens if I call 'new' twice in a row?  Sounds like I'm going
  55. |         to make some memory become unrecoverable.  
  56.  
  57. The memory allocated by the first call to new would "leak" out of your
  58. application.  You would never be able to put it back in the heap.
  59.  
  60.  
  61. --
  62. Robert Martin                        Training courses offered in:
  63. R. C. M. Consulting                       Object Oriented Analysis
  64. 2080 Cranbrook Rd.                        Object Oriented Design
  65. Green Oaks, Il 60048 (708) 918-1004       C++
  66.