Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Overloading New Operator (http://www.velocityreviews.com/forums/t267725-overloading-new-operator.html)

Min 06-25-2003 07:16 PM

Overloading New Operator
 
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 = ::operator 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 ?



Ron Natalie 06-25-2003 07:37 PM

Re: Overloading New Operator
 

"Min" <nobody@home.com> wrote in message news:JymKa.307861$Vi5.8158989@news1.calgary.shaw.c a...

> 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 ::operator new(size);
right from the try block.




All times are GMT. The time now is 03:57 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.