Overloading New Operator

Discussion in 'C++' started by Min, Jun 25, 2003.

  1. Min

    Min Guest

    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 ?
    Min, Jun 25, 2003
    #1
    1. Advertising

  2. Min

    Ron Natalie Guest

    "Min" <> wrote in message news:JymKa.307861$...

    > 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.
    Ron Natalie, Jun 25, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Smith
    Replies:
    2
    Views:
    420
    Ivan Vecerina
    Oct 6, 2004
  2. Replies:
    11
    Views:
    728
    James Kanze
    May 16, 2007
  3. hurcan solter
    Replies:
    3
    Views:
    728
    Cholo Lennon
    Aug 29, 2007
  4. Replies:
    11
    Views:
    558
  5. Replies:
    2
    Views:
    311
Loading...

Share This Page