重载全局new和delete
当全局版本的new和delete不能满足整个系统时,对其重载是很极端的方法
重载的new必须有一个size_t参数
operator new()的返回值是一个void*,而不是指向如何特定类型的指针
operator delete()的参数是一个指向由operator new()分配的内存的void*
重载全局new 和delete
//: C13:GlobalOperatorNew.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Overload global new/delete
#include <cstdio>
#include <cstdlib>
using namespace std;
void* operator new(size_t sz) {
printf("operator new: %d Bytes\n", sz);
void* m = malloc(sz);
if(!m) puts("out of memory");
return m;
}
void operator delete(void* m) {
puts("operator delete");
free(m);
}
class S {
int i[100];
public:
S() { puts("S::S()"); }
~S() { puts("S::~S()"); }
};
int main() {
puts("creating & destroying an int");
int* p = new int(47);
delete p;
puts("creating & destroying an s");
S* s = new S;
delete s;
puts("creating & destroying S[3]");
S* sa = new S[3];
delete []sa;
getchar();
} ///:~
重载new和delete的通常形式。这里的内存分配使用了标准C库函数malloc()
和free()
在main()里,创建内建数据类型对象以证明在这种情况下也调用重载的new和
delete
输出
creating & destroying an int
operator new: 4 Bytes
operator delete
creating & destroying an s
operator new: 400 Bytes
S::S()
S::~S()
operator delete
creating & destroying S[3]
operator new: 1204 Bytes
S::S()
S::S()
S::S()
S::~S()
S::~S()
S::~S()
operator delete