Call a new class statement

An expression operator new(sizeof(T))allocates Tbytes through ::operator new, right?

Is there a way to call the version class class operator new, if one exists, in the same way as new T()allocating memory (before calling the constructor)?

T::operator new(sizeof(T))gives a compile-time error if it Tdoes not define it operator new, even if it Tinherits the base class that defines it. I would like to name:

  • Foo::operator newif Foodeterminesoperator new
  • Base::operator newif Foocomes from Basewhich defines operator new(what should I do with multiple inheritance?)
  • ::operator new otherwise
+3
source share
2 answers

, -, , .

, , , . , , .

, , , / , : object_allocator<T>::allocate() . - new - , , .

+1

allocate 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;
}
0

Source: https://habr.com/ru/post/1750990/


All Articles