Overloading New Operator

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Min

    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

    #2
    Re: Overloading New Operator


    "Min" <nobody@home.co m> wrote in message news:JymKa.3078 61$Vi5.8158989@ news1.calgary.s haw.ca...
    [color=blue]
    > void main()[/color]

    main returns int.
    [color=blue]
    > {
    > 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.[/color]
    [color=blue]
    > 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 ?
    >[/color]
    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.


    Comment

    Working...