码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 重载new和delete

时间:2014-12-25 01:28:34      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

下边代码对new和delete进行了简单的重载:

#include <memory>
#include <iostream>
#include <cstddef>
using namespace std;
class TraceHeap
{
    int i;
public:
    static void* operator new(size_t siz)
    {
        void* p = ::operator new(siz);
        cout << "Allocating TraceHeap object on the heap "
            << "at adress " << p << endl;
        return p;
    }
    static void operator delete(void* p)
    {
        cout << "Deleting TraceHeap object at address "
            << p <<endl;
        ::operator delete(p);
    }

    TraceHeap(int i) : i(i) {}
    int getVal()  const { return i; }
};
int main()
{
    auto_ptr<TraceHeap> pMyObject(new TraceHeap(5));
    cout << pMyObject->getVal() << endl;    // Pringts 5
    getchar();
}

 

运行结果:

技术分享

C++ 重载new和delete

标签:

原文地址:http://www.cnblogs.com/AmitX-moten/p/4183725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!