读书人

C++ new/delete 满载

发布时间: 2013-10-27 15:21:50 作者: rapoo

C++ new/delete 重载
首先,new和delete是运算符,重载new和delete是可能的。这样做的原因是,有时希望使用某种特殊的动态内存分配方法。例如,可能有些分配子程序,他们的堆已耗尽,自动开始把一个磁盘文件当虚存储使用,或者用户希望控制某一片存储空间的分配等。

重载new和delete的格式如下:

#include <iostream>#include <stdlib.h>#include <string.h>using namespace std;class three_d{private:    int x,y,z;public:    three_d(int a,int b,int c);    ~three_d()    {        cout << "Destructing\n";    }    friend ostream & operator <<(ostream &stream,three_d obj);};three_d::three_d(int a,int b,int c){    cout << "Constructing\n";    x = a;    y = b;    z = c;}void *operator new(size_t size){    cout << "in threee_d new\n";    return malloc(size);}void operator delete(void *p){    cout << "in three_d delete\n" ;    free(p);}ostream &operator <<(ostream &os,three_d obj){    os << obj.x << ",";    os << obj.y << ",";    os << obj.z << "\n";    return os;}int main(int argc,char *argv[]){    three_d *p = new three_d(1,2,3);    three_d *p1 = new three_d(4,5,6);    if(!p || !p1)    {        cout << "Allocation failure" << endl;        return 1;    }    cout << *p << *p1;    delete p;    delete p1;    int *pnum;    pnum = new int;    *pnum = 0;    cout << "num = " << *pnum << endl;    delete pnum;    cout << "Application Run Successfully!" << endl;    return 0;}

读书人网 >C++

热点推荐