Lighter wrote:
The C++ Standard Doesn't Permit Overloading new and delete?
In the 13.5 of The C++ standard (ISO/IEC 14882, 1998), I cannot find
the specification on overloading the operators new and delete; however,
many C++ books including "C++ Primer" say that the operators new and
delete can be overloaded. I wonder if this has definitive
specification? Who can tell me?
Many thanks to those who answer.
To understand this you need to find a stash of whatever special brand of
crack the designers were on when they came up with the terminology. You
can't overload the "new operator", but you can overload "operator new".
The "new operator" is what you get with a statement like:
T * pt = new T(5) ;
This has two jobs. It always does these two things, and there is
nothing you can do to change that behavior:
1. Allocate some memory.
2. Construct an object in that memory.
Step 2 is accomplished, rather obviously, by calling the object's
constructor. Step 1 is accomplished by calling .. wait for it ..
"operator new". You could call "operator new" yourself if you wanted to
get some uninitialized memory, with a statement like:
void * pmem = operator new(1024) ; // Allocate 1024 bytes of memory.
You can also replace "operator new" (overload may not be the right
terminology), for example:
void * operator new(std::size_t sz) throw(std::bad_alloc)
{
std::cout << "Global operator new called." << std::endl ;
void * p = ::malloc(sz) ;
if (!p)
throw std::bad_alloc() ;
return p ;
}
Or you can replace "operator new" for a specific class:
class T
{
public:
void * operator new(std::size_t sz) throw(std::bad_alloc)
{
std::cout << "T::operator new called." << std::endl ;
return ::operator new(sz) ; // Use global operator new.
}
} ;
There is an analogous relationship between the "delete operator" and
"operator delete".
(Note: Most of my information courtesy of Item 8 in Scott Meyers' More
Effective C++.)
--
Alan Johnson