C++ Virtual operator delete?

前端 未结 4 1508
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 05:59

Is it possible to have a virtual delete operator? I\'m not talking destructor, I mean the actual operator overload.

Minus the fact that it is (in most cases) a big

4条回答
  •  春和景丽
    2020-12-31 06:31

    No -- even if you don't mark it as such, when/if you overload new/delete for a class, they end up as static member functions1, and static member functions can't be virtual.

    To work, they really need to be static -- they're used to allocate/free the memory for an object, so have to happen before the object starts construction/after it finishes destruction. You clearly can't have it allocate the memory for what will eventually become an instance of a class, and at the same time have it depend on that already being an instance of the class (which a virtual function does).


    1. §12.5/1:

    Any allocation function for a class T is a static member (even if not explicitly declared static).

    and §12.5/6:

    Any deallocation function for a class X is a static member (even if not explicitly declared static).

    ...for anybody who cares about the official statements. Interesting how it's a "class T" when you're allocating, and a "class X" when you're freeing.

提交回复
热议问题