🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #1690

Re: overloaded new/delete

#1690
From: Steve Clamage
Date: Wed, 09 Aug 1995 15:26
65 lines
2461 bytes
In article nta@oznet03.ozemail.com.au, agray@ozemail.com.au (Alan Gray) writes:
>I pose the following problem.
>
>Given a personalised allocator
>
>    class Malloc {
>
>    public:
>
>      Malloc();
>
>      void *allocate(size_t sz);
>      void  deallocate(void *ptr);
>    };
>
>    void *operator new(size_t sz,Malloc *m=0)	<=== this will cause an ambiguity
>    // ------------------------------------------------
>    // here sz == sizeof(class/struct)
>    // ------------------------------------------------
>    {
>      if(m) {
>        return(m->allocate(sz));
>      } else {
>        return(::operator new(sz));		<=== ambiguous call
>      }
>    }


Both the predefined operator new and your placement version can be called
with a single size_t argument. You have to remove the default argument
value, which will give the effect you appear to want.
	void* operator new(size_t sz, Malloc* m)
	{
		if( m ) return m->allocate(sz);
		... otherwise do something about the error
	}
Thus:
	... new T ... // uses predefined operator new
	... new (&allocator) T ... // uses your operator new

>
>do we need to be able to overload as follows
>
>    void operator delete(void *ptr,Malloc *m=0) ... <=== same ambiguity problem
>
> ... The draft standard does not cover this.

It is covered. There is no syntax for getting an overloaded operator delete
via a delete-expression. You can define a "placement delete", but it is
called only if
 - a constructor invoked from a placement-new expression exits via an exception, or
 - you call the operator delete explicitly.
That is:
	T* p ...
	delete p; // never calls a placement delete
	// but you can do this
	p->~T(); // call destructor
	operator delete(p, &allocator);

You can use class-specific operator new and delete in an Allocator base
class, and these will be inherited by any class derived from Allocator.
You can find examples of how to do this in "The C++ Programming
Language", 2nd edition and in other books.
---
Steve Clamage, stephen.clamage@eng.sun.com
Technical Details
Message-ID: <40ak2i$9oa@engnews2.Eng.Sun.COM>
Path: arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!usenet
References: <409muv$nta@oznet03.ozemail.com.au>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!usenet
From: clamage@Eng.Sun.COM (Steve Clamage)
Newsgroups: comp.std.c++
Subject: Re: overloaded new/delete
Date: 9 Aug 1995 15:26:10 GMT
Organization: Sun Microsystems Inc.
Message-ID: <40ak2i$9oa@engnews2.Eng.Sun.COM>
References: <409muv$nta@oznet03.ozemail.com.au>
Reply-To: clamage@Eng.Sun.COM
NNTP-Posting-Host: taumet.eng.sun.com