勤能补拙,厚积薄发

合抱之木,生于毫末;九层之台,起于垒土;千里之行,始于足下
随笔 - 19, 文章 - 0, 评论 - 3, 引用 - 0
数据加载中……

Effective C++学习(item50)

自定制operator new
代码如下:
 1 #include <iostream>
 2 #include <cstdlib>
 3 static const int signature = 0xDEADBEEF;// signature, log in the new assigned memory 
 4 typedef unsigned char Byte;
 5 // the decorated malloc 
 6 void* operator new(std::size_t size) throw(std::bad_alloc)
 7 {
 8     using namespace std;
 9     size_t realSize = size + 2 * sizeof(int);
10     void* pMem = malloc(realSize);
11     if (!pMem) throw bad_alloc();
12 
13     *(static_cast<int*>(pMem)) = signature;
14     *(reinterpret_cast<int*>(static_cast<Byte*>(pMem) + sizeof(int)
15                    + size)) = signature;
16     return static_cast<Byte*>(pMem) + sizeof(int);
17 }

在gcc4.4.1下编译通过

posted on 2011-11-09 10:45 lee007 阅读(314) 评论(0)  编辑 收藏 引用 所属分类: Programming Study


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理