开发者

inherit operator new from base class

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 { r开发者_如何学运维eturn _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 the derived class has no data members, then i think sizeof(derived) == sizeof(Link) and the assertion in op new in Link will not fail.

class derived : public Link {};

derived* d = new derived(); //should call Link's op new 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜