// 52-2.cpp
#include <iostream>
#include <string>
using namespace std;
class Test
static unsigned int c_count;
static char* c_buffer;
static char* c_map;
int m_value;
public:
static bool SetMemorySource(char* memory, unsigned int size)
bool ret = false;
c_count = size / sizeof(Test);
ret = c_count && (c_map = reinterpret_cast<char*>(calloc(c_count, sizeof(char))));
if (ret)
c_buffer = memory;
free(c_map);
c_map = NULL;
c_buffer = NULL;
c_count = 0;
return ret;
void* operator new (unsigned int size)
void* ret = NULL;
if (c_count > 0)
for (int i = 0; i < c_count; i++)
if (!c_map[i])
c_map[i] = 1;
ret = c_buffer + i * sizeof(Test);
cout << "succeed to allocate memory: " << ret << endl;
break;
ret = malloc(size);
return ret;
void operator delete(void* p)
if (p != NULL)
if (c_count > 0)
char* mem = reinterpret_cast<char*>(p);
int index = (mem - c_buffer) / sizeof(Test);
int flag = (mem - c_buffer) % sizeof(Test);
if (flag == 0 && 0 <= index && index < c_count)
c_map[index] = 0;
cout << "succeed to free memory: " << p << endl;
free(p);
unsigned int Test::c_count = 0;
char* Test::c_buffer = NULL;
char* Test::c_map = NULL;
int main(int argc, char* argv[])
char buffer[12] = { 0 };
Test::SetMemorySource(buffer, sizeof(buffer));
cout << "==== Test Single Object ====" << endl;
Test* pt = new Test;
delete pt;
cout << "==== Test Object Array ====" << endl;
Test* pa[5] = { 0 };
for (int i = 0; i < 5; i++)
pa[i] = new Test;
cout << "pa[" << i << "]" << pa[i] << endl;
for (int i = 0; i < 5; i++)
cout << "delete " << pa[i] << endl;
delete pa[i];
return 0;
main 函数中的 buffer[12] 在栈中分配空间,将这个地址指定为 new 申请对象的地址,则 new 在栈中分配空间。
C++ 类中成员函数,static 变量不计算入 sizeof,buffer[12] 大小为 12 个字节,Test 大小为 4 字节,所以最多可以放置三个对象,我们申请了 5 个对象,所以只有前三个对象对申请成功。
==== Test Single Object ====
succeed to allocate memory: 00B5FE20
succeed to free memory: 00B5FE20
==== Test Object Array ====
succeed to allocate memory: 00B5FE20
pa[0]00B5FE20
succeed to allocate memory: 00B5FE24
pa[1]00B5FE24
succeed to allocate memory: 00B5FE28
pa[2]00B5FE28
pa[3]00000000
pa[4]00000000
delete 00B5FE20
succeed to free memory: 00B5FE20
delete 00B5FE24
succeed to free memory: 00B5FE24
delete 00B5FE28
succeed to free memory: 00B5FE28
delete 00000000
delete 00000000
1、new/delete 操作符可以重载,推荐针对具体类重载
2、new 默认在堆上分配空间,重载可以在静态存储区、栈上分配空间