This page (from C++ in action book) shows code:
class Link
{
friend class FreeList;
public:
Link (Link * pNext, int id)
: _pNext (pNext), _id (id) {}
Link * Next () const { return _pNext; }
int Id () const { return _id; }
// allocator
void * operator new (size_t size)
{
assert (size == sizeof (Link));
return _freeList.NewLink ();
}
void operator delete (void * mem)
{
if (mem)
_freeList.Recycle (mem);
}
static void Purge () { _freeList.Purge (); }
private:
static FreeList _freeList;
Link * _pNext;
int _id;
};
And then say
Class Link has a static member _freeList which is used by the overloaded class-specific operators new and delete. Notice the assertion in operator new. It protects us from somebody calling this particular operator for a different class. How could that happen? Operators new and delete are inherited. If a class derived from Link didn't override these operators, new called for the derived class would return an object of the wrong size (base-class size).
Is this saying true? I think new will be called with right size of derived object. Why not?
A new
expression will cause an allocation function (operator new
) to be called with the correct size for the object being constructed. That's what the size_t
parameter for operator new
is for.
The particular implementation of operator new
in the example, however, can only cope with uniform sized allocation requests. If a derived class didn't override operator new
this implementation of operator new
would be called with a size that it can't cope with (aka "wrong").
It is, in general, perfectly possible to write an operator new
for a class that can handle allocation requests for derived classes.
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