home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / cplus / 18245 < prev    next >
Encoding:
Text File  |  1992-12-21  |  2.0 KB  |  63 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!cs.utexas.edu!qt.cs.utexas.edu!yale.edu!think.com!sdd.hp.com!caen!uvaarpa!murdoch!virginia.edu!gs4t
  3. From: gs4t@virginia.edu (Gnanasekaran Swaminathan)
  4. Subject: Re: overloading operator new
  5. Message-ID: <1992Dec19.195013.20805@murdoch.acc.Virginia.EDU>
  6. Sender: usenet@murdoch.acc.Virginia.EDU
  7. Organization: University of Virginia
  8. References:  <1992Dec18.125656.4293@meadow.uucp>
  9. Date: Sat, 19 Dec 1992 19:50:13 GMT
  10. Lines: 51
  11.  
  12. marc@meadow.uucp (Marc Riehm) writes:
  13. : My Turbo C++ 2.0 manual (the only C++ documentation I have available :( )
  14. : says that the first argument of MyObject::new must be a size_t.  i.e. we
  15. : overload new via a method which looks like...
  16. : void *MyObject::new(size_t)
  17. : They imply that there can be other arguments to MyObject::new.  Could anyone
  18. : tell me whether or not this is true and, if it is, how to declare the method
  19. : and how to use MyObject::new?  Are there any side effects on the constructor?
  20.  
  21. First, you have to keep in mind that implementations are allowed to
  22. call operator new before calling constructors when you provide your
  23. own operator new.
  24.  
  25. If you are going to use your own memory allocation scheme,
  26. it will be easier to provide global operator new than
  27. providing member operator new for each and every class.
  28.  
  29. If, on the other hand, you want to do specialized memory
  30. allocation for some classes, you can do so by providing
  31. member operator new to those classes.
  32.  
  33. For example,
  34.  
  35. class Pool {
  36.     // memory pool class
  37. public:
  38.     void*    getmem (size_t sz);
  39.     void    freemem (void* p);
  40. };
  41.  
  42. class A {
  43.     //...
  44. public:
  45.     A (int a) {...}
  46.     ~A () {...}
  47.  
  48.     void*    operator new (size_t sz, Pool& p) { return p.getmem (sz); }
  49.     // since the above op new hides ::new, you may
  50.     // need the following op new as well
  51.     void*    operator new (size_t sz) { return ::new char[sz]; } 
  52.     void    operator delete (void* p) {
  53.         /* special allocation may require special deletion */
  54.     }    
  55. };
  56.  
  57. main ()
  58. {
  59.     Pool p;
  60.     A*    a = new (p) A (5);
  61.     // note the way the extra argument to A::operator new is passed.
  62. }
  63.