#include <iostream>
#include <cstdlib>
using namespace std;
class Foo{
private:
int _id;
public:
Foo(int id):_id(id){
cout<<"Foo(int id) id:"<<id<<endl;
}
Foo():_id(0){
};
static void* operator new(size_t size){
void *ptr;
cout<<"new size:"<<size<<endl;
ptr = malloc(size);
cout<<"new ptr:"<<ptr<<endl;
return ptr;
}
static void* operator new[] (size_t size){
cout<<"new [] size:"<<size<<endl;
return malloc(size);
}
static void operator delete (void *ptr, size_t size){
cout<<"delete size:"<<size<<endl;
cout<<"delete ptr:"<<ptr<<endl;
free(ptr);
}
static void operator delete [](void *ptr, size_t size){
cout<<"delete [] size :"<<size<<endl;
free(ptr);
}
};
int main(){
Foo *p = new Foo(2);
delete p;
cout<<"------------------"<<endl;
Foo* ptr = new Foo[3];
delete []ptr;
cout<<endl;
return 0;
}
输出:
new size:4
new ptr:0x315a0
Foo(int id) id:2
delete size:4
delete ptr:0x315a0
------------------
new [] size:16
delete [] size :16
本文深入探讨了C++中自定义new和delete运算符的方法,通过一个具体的类Foo演示了如何覆盖这些运算符以实现内存的精细控制。文章详细展示了Foo类如何通过malloc和free进行内存分配和释放的过程,并附上了完整的代码示例和运行输出。
421

被折叠的 条评论
为什么被折叠?



