C++ 类里重载new和delete必须为static成员函数

2,554 阅读1分钟

参考类如下:

class Base {
public:
    static void* operator new(std::size_t size)
    {
        // 此段实现参考 effective c++ P254
        if (sizeof(Test) != size) {
            cout << "call system operator new" << endl;
            return ::operator new(size);
        } else {
            cout << "call self operator new" << endl;
        }
    }
private:
    int x;
};

class Dirived : public Base {
private:
    int a;
};

int main()
{
    Test* t = new Test();
    Dirived* d = new Dirived();
    return 0;
}

首先,c++标准中有这么一句话:

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

其次,new对象时,对象还没有,设置成类非静态成员函数是没意思的,隐藏的this指针无从下手,所以要声明为static函数。

再者,因为标准要求operator new()的第一个参数类型必须是std::size_t,而成员函数的第一个参数是T* const this,也许这也算一个理由??

上述源码编译执行的结果为:

call self operator new
call system operator new

new Test() 的底层会先调用operator new()函数,该函数的参数即为 sizeof(Test),这些都是系统默默完成的,然后调用Test的默认构造函数。

参考链接:bbs.csdn.net/topics/3702…
参考书目:《Effective c++》条款51