5

This is a follow up to my previous question,

Initializing a class using malloc

Accepted answer on the question works and gives me new/delete on the avr-gcc, here is the problem but my overloaded new delete wracks havoc on regular gcc, what is the proper way to overload new delete all my classes derive from a common base class so ideally i would like to just override new delete for my object so it does not mess with stl stdlib etc.

Community
  • 1
  • 1
Hamza Yerlikaya
  • 49,047
  • 44
  • 147
  • 241

2 Answers2

8

'new' and 'delete' can overloaded inside the common Object base class. So, that will be applicable only to that hierarchy.

class Object {
public:
  void* operator new (size_t size);
  void operator delete (void *p);
};

class Derived : public Object {
// uses the above versions of new/delete
};

[Note: It's an added advantage for you as all your class are getting derived from a common Object class (as mentioned in your question and the link)]

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • There is no common "Object" base class. You're thinking of Java/C# land. :) – Billy ONeal May 02 '11 at 15:50
  • @Billy, OP has mentioned in his question `all my classes derive from a common base class` and in his linked question he has named it as `Object`. – iammilind May 02 '11 at 15:52
3

Overload the new & delete inside your own class & not Globally.
For eg: If name of your common class is YourClass, You can overload them as follows:

void *YourClass::operator new(size_t size)
{
    void *p;
    cout << "In overloaded new.";
    p =  malloc(size);
    if(!p) 
    {
        throw std::bad_alloc;  //Throw directly than with named temp variable
    }
    return p;
}

void YourClass::operator delete(void *p)
{
    cout << "In overloaded delete.\n";
    free(p);
}

void *YourClass::operator new[](size_t size)
{
    void *p;
    cout << "Using overload new[].\n";
    p =  malloc(size);
    if(!p) 
    {
        throw std::bad_alloc;
    }
    return p;
}

void YourClass::operator delete[](void *p)
{
    cout << "Free array using overloaded delete[]\n";
    free(p);
}

All classes derived from YourClass will be able to use these overloaded new and delete operators.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • Why not just `throw std::bad_alloc;` ? No reason to create a named variable for that. – Billy ONeal May 02 '11 at 15:54
  • @Billy ONeal: Corrected. Just caught me while I was just about to edit the first version :) – Alok Save May 02 '11 at 15:58
  • @Hamza Yerlikaya: Since you overload them specifically for your own class, the operators will be invoked only for objects of your class. All other objects will use global new and delete. If you don't need exceptions probably you should overload `nothrow` version of new. – Alok Save May 02 '11 at 16:06