home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!cs.utexas.edu!qt.cs.utexas.edu!yale.edu!think.com!sdd.hp.com!caen!uvaarpa!murdoch!virginia.edu!gs4t
- From: gs4t@virginia.edu (Gnanasekaran Swaminathan)
- Subject: Re: overloading operator new
- Message-ID: <1992Dec19.195013.20805@murdoch.acc.Virginia.EDU>
- Sender: usenet@murdoch.acc.Virginia.EDU
- Organization: University of Virginia
- References: <1992Dec18.125656.4293@meadow.uucp>
- Date: Sat, 19 Dec 1992 19:50:13 GMT
- Lines: 51
-
- marc@meadow.uucp (Marc Riehm) writes:
- : My Turbo C++ 2.0 manual (the only C++ documentation I have available :( )
- : says that the first argument of MyObject::new must be a size_t. i.e. we
- : overload new via a method which looks like...
- : void *MyObject::new(size_t)
- : They imply that there can be other arguments to MyObject::new. Could anyone
- : tell me whether or not this is true and, if it is, how to declare the method
- : and how to use MyObject::new? Are there any side effects on the constructor?
-
- First, you have to keep in mind that implementations are allowed to
- call operator new before calling constructors when you provide your
- own operator new.
-
- If you are going to use your own memory allocation scheme,
- it will be easier to provide global operator new than
- providing member operator new for each and every class.
-
- If, on the other hand, you want to do specialized memory
- allocation for some classes, you can do so by providing
- member operator new to those classes.
-
- For example,
-
- class Pool {
- // memory pool class
- public:
- void* getmem (size_t sz);
- void freemem (void* p);
- };
-
- class A {
- //...
- public:
- A (int a) {...}
- ~A () {...}
-
- void* operator new (size_t sz, Pool& p) { return p.getmem (sz); }
- // since the above op new hides ::new, you may
- // need the following op new as well
- void* operator new (size_t sz) { return ::new char[sz]; }
- void operator delete (void* p) {
- /* special allocation may require special deletion */
- }
- };
-
- main ()
- {
- Pool p;
- A* a = new (p) A (5);
- // note the way the extra argument to A::operator new is passed.
- }
-