C++ new/delete操作符重载

C++ new/delete操作符重载

本文简单实验了 C++ new/delete 操作符的重载,全局重载和具体类的重载。
在此基础之上可以实现在堆上的内存分配的跟踪和对象池。
代码如下:

#include 
#include 

using namespace std;

class A {
public:
    void Print() { cout << " A Class " << endl; }   
};

class B {
public:
    void Print() { cout << " B Class " << endl; }   
};

class C {
public:
    void * operator new(size_t size)
    {
        cout << " Class C new operator ... " << endl;
        return malloc(size);
    }
    void operator delete(void *p)
    {
        cout << " Class C delete operator ... " << endl;
        free(p);
    }
public:
    void Print() { cout << " C Class " << endl; }   
};

void * operator new(size_t size)
{
    cout << " Global new operator ... " << endl;
    return malloc(size);
}

void operator delete(void * p)
{
    cout << " Global delete operator ... " << endl;
    free(p);
}

int main(int argc, char** argv) {

    A *a = new A;
    a->Print();
    delete a;

    B *b = new B;
    b->Print();
    delete b;

    C *c = new C;
    c->Print();
    delete c;

    return 0;
}

C++ new/delete操作符重载_第1张图片
定义三个类:A、B和C, 只有C中重载了自己的new/delete操作符。结果显示没有重载new/delete操作符的
构造时使用全局的new/delete操作符,C就是创建时屏蔽全局new/delete操作符,使用自己的操作符。

你可能感兴趣的:(随笔)