tags:

views:

45

answers:

2

The expression operator new(sizeof(T)) allocates T bytes via ::operator new, correct?

Is there any way to call the class-specific version of operator new if it exists, exactly the way how new T() allocates memory (before calling the constructor)?

T::operator new(sizeof(T)) gives a compile-time error if T does not define operator new, even if T inherits from a base class that defines it. What I would like to call is:

  • Foo::operator new if Foo defines operator new
  • Base::operator new if Foo derives from Base that defines operator new (what do I do about multiple inheritance?)
  • ::operator new otherwise
A: 

Define a differ static function allocate and call this function from T::operator new

class X {
public:
    static void * allocate(size_t size) {
           //...
    }
    void *operator new(size_t size) {
       return allocate(size);
    }
};

void f() {
   void * p = X::allocate(sizeof(X));
   X * x = new(p) X;
}
Alexey Malistov
That solution is too intrusive for my taste :(
FredOverflow
A: 

The standard library solves this problem using an allocator object whose type is set as a template parameter of the class that needs a customizable allocation algorithm.

I don't think there's any complete way to do what you asked, as already evidenced by your second bullet. There's no way for the compiler to know which parent's operator new to use if they both defined one.

If you're trying to implement for example a small object allocator pool that picks an appropriate size/pool at compile time, what about using a standalone template allocator function: It would be called something like object_allocator<T>::allocate() and the template type would let you figure out the size automatically. You still can't inherit operator new because of the multiple inheritance issue but it makes it easy to figure out how to allocate memory within any class.

Mark B