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 newBase::operator new if Foo derives from Base that defines operator new (what do I do about multiple inheritance?)::operator new otherwiseThe 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With