Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size information when overloading C++ new operator

The C++ memory allocation operator has the form of operator new (size_t s). When I overload the new operator for a class object of type T, does it guarantee the input argument (i.e., size_t s) of the operator new is exactly sizeof(T)? If yes, why does this function still need the size as input argument?

like image 911
Jes Avatar asked Dec 18 '15 06:12

Jes


1 Answers

It is possible to override operator new in a base class and use it to allocate objects of derived class type.

struct Base
{
    void* operator new (size_t s) { ... }
    int a;
};

struct Derived : public Base
{
   int b;
};

Derived* d = new Derived; 

When allocating memory for Derived, Base::operator new(size_t) will be used. The value of the argument will be sizeof(Derived). Without that argument, we cannot allocate the right amount of memory for an object of type Derived.

like image 106
R Sahu Avatar answered Sep 27 '22 22:09

R Sahu