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?
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.
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