Overloading New Operator

M

Min

class Foo
{
public:
char name[20];
Foo() { /*** Do Something ***/ }
Foo( char* str) { /*** Do Something ***/ }

static void * operator new(unsigned int size)
{
//*********************
// Code from Effective C++
//*********************
void* memory = null;
if ( size == 0 ) { size = 1; }
try
{
memory = ::eek:perator new(size);
}
catch (std::bad_alloc&)
{
throw;
}
return memory;
}
};

void main()
{
Foo * ptrFoo1 = new Foo(); // Uses Overloaded New
Foo * ptrFoo2 = new Foo("What's up"); // Uses Overloaded New
Foo *ptrFoo3 = new Foo[10]; // Uses DEFAULT New.
}

//*******************************************
Using a debugger (VC++ 6.0 if it is important), I find that ptrFoo3 does not
use the overloaded new operator. Anybody knows why ? or if I am missing
something. Or is it the vendor ? or language ?
 
R

Ron Natalie

Min said:
void main()

main returns int.
{
Foo * ptrFoo1 = new Foo(); // Uses Overloaded New
Foo * ptrFoo2 = new Foo("What's up"); // Uses Overloaded New
Foo *ptrFoo3 = new Foo[10]; // Uses DEFAULT New.
Using a debugger (VC++ 6.0 if it is important), I find that ptrFoo3 does not
use the overloaded new operator. Anybody knows why ? or if I am missing
something. Or is it the vendor ? or language ?
You're missing something. Arrays use the operator new[] allocation function
(which you haven't overloaded).

I'll take your word for the fact you cobbed that allocator form a book, but it's
overly silly:
1. the size_t arg will never be zero (unless some clown explicitly calls it that way)
and it's not clear why you want to bump it up in that case anyhow.
2. The catch block that does nothing other than rethrow is a bit silly.
3. You could just
return ::eek:perator new(size);
right from the try block.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top