home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!decwrl!world!wmm
- From: wmm@world.std.com (William M Miller)
- Subject: Re: error in Stroustrup text (?)
- Message-ID: <BsvF46.1EH@world.std.com>
- Organization: Software Emancipation Technology, Inc.
- References: <46960007@hpscit.sc.hp.com>
- Date: Wed, 12 Aug 1992 12:38:29 GMT
- Lines: 64
-
- In article <46960007@hpscit.sc.hp.com>, Greg Weeks writes:
- > Someone please correct me if I'm mistaken, but the following text from pg
- > 216 of Stroustrup's 2nd edition C++ text seems to be wrong:
- >
- > If you want to supply an allocator/dealocator pair that works correctly
- > for derived classes, you must either supply a virtual destructor in the
- > base class or refrain from using the size_t argument in the
- > deallocator.
- >
- > _Whenever_ a derived class object may be deleted through a pointer to base
- > object, a virtual destructor is required. It does not suffice to refrain
- > from using the size_t argument in the deallocator. The reason is that
- > `delete' needs to know both the size _and_ the location of the thing to be
- > deleted; and the location of the derived object may differ from the
- > location of the base object. (That is, it may be that (void*)pd is
- > different from (void*)pb.)
- >
- > Right?
-
- True, but that's irrelevant to the point of the text you cited. In
- the code below, for instance, the derived-class object is deleted by
- means of a derived-class pointer, but you can still get the wrong size
- in operator delete():
-
- #include <stddef.h>
- #include <iostream.h>
-
- class base {
- public:
- void* operator new(size_t sz) {
- cout << "allocating " << sz << " bytes.\n";
- return new char[sz];
- }
-
- void operator delete(void* p, size_t sz) {
- cout << "freeing " << sz << " bytes.\n";
- delete [] (char*) p;
- }
-
- private:
- int i;
- };
-
- class derived: public base {
- int j;
- };
-
- int main() {
- derived* d = new derived;
- delete d;
- return 0;
- }
-
- The result of running this code (under cfront 2.1 on a Sun, at least)
- is:
-
- allocating 8 bytes.
- freeing 4 bytes.
-
- Adding a virtual destructor allows the correct size of the object to
- be passed to operator delete().
-
- -- William M. Miller, wmm@world.std.com
-
-