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. Advertisements

  2. Min

    Ron Natalie Guest

    main returns int.
    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. Advertisements

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 (here). After that, you can post your question and our members will help you out.