home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #18 / NN_1992_18.iso / spool / comp / lang / cplus / 12262 next >
Encoding:
Text File  |  1992-08-12  |  2.2 KB  |  75 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!decwrl!world!wmm
  3. From: wmm@world.std.com (William M Miller)
  4. Subject: Re: error in Stroustrup text      (?)
  5. Message-ID: <BsvF46.1EH@world.std.com>
  6. Organization: Software Emancipation Technology, Inc.
  7. References: <46960007@hpscit.sc.hp.com>
  8. Date: Wed, 12 Aug 1992 12:38:29 GMT
  9. Lines: 64
  10.  
  11. In article <46960007@hpscit.sc.hp.com>, Greg Weeks writes:
  12. > Someone please correct me if I'm mistaken, but the following text from pg
  13. > 216 of Stroustrup's 2nd edition C++ text seems to be wrong:
  14. >     If you want to supply an allocator/dealocator pair that works correctly
  15. >     for derived classes, you must either supply a virtual destructor in the
  16. >     base class or refrain from using the size_t argument in the
  17. >     deallocator.
  18. > _Whenever_ a derived class object may be deleted through a pointer to base
  19. > object, a virtual destructor is required.  It does not suffice to refrain
  20. > from using the size_t argument in the deallocator.  The reason is that
  21. > `delete' needs to know both the size _and_ the location of the thing to be
  22. > deleted; and the location of the derived object may differ from the
  23. > location of the base object.  (That is, it may be that (void*)pd is
  24. > different from (void*)pb.)
  25. > Right?
  26.  
  27. True, but that's irrelevant to the point of the text you cited.  In
  28. the code below, for instance, the derived-class object is deleted by
  29. means of a derived-class pointer, but you can still get the wrong size
  30. in operator delete():
  31.  
  32.     #include <stddef.h>
  33.     #include <iostream.h>
  34.  
  35.     class base {
  36.     public:
  37.        void* operator new(size_t sz) {
  38.           cout << "allocating " << sz << " bytes.\n";
  39.           return new char[sz];
  40.        }
  41.  
  42.        void operator delete(void* p, size_t sz) {
  43.           cout << "freeing " << sz << " bytes.\n";
  44.           delete [] (char*) p;
  45.        }
  46.  
  47.     private:
  48.        int i;
  49.     };
  50.  
  51.     class derived: public base {
  52.        int j;
  53.     };
  54.  
  55.     int main() {
  56.        derived* d = new derived;
  57.        delete d;
  58.        return 0;
  59.     }
  60.  
  61. The result of running this code (under cfront 2.1 on a Sun, at least)
  62. is:
  63.  
  64.         allocating 8 bytes.
  65.     freeing 4 bytes.
  66.  
  67. Adding a virtual destructor allows the correct size of the object to
  68. be passed to operator delete().
  69.  
  70. -- William M. Miller, wmm@world.std.com
  71.  
  72.