1、引言
本篇介绍new和delete的内存管理以及operator new/new[]和operator delete/delete[]的重载方法。
2、new的内存分配
注意点:
a、如上图构造一个复数对象,使用new方法,存放指针pc,编译器在构造过程中会分成三个步骤:①分配内存(使用operator new());②转型;③调用构成函数;
b、这个过程的简单理解就是先分配一块内存给声明对象,然后往对象中添加数据。
3、delete的内存管理
注意点:
a、如上图使用delete pc。编译器会转化为两个步骤:①调用析构函数;②释放内存(使用operator delete())。
b、这个过程简单的理解就是先清理数据,再释放指针。
4、关于new和delete的重载
1)头文件示例
class Foo
{
public:
Foo() :_id(0){
cout << "default ctor.this = " << this << " id = " << _id << "\n";
}
Foo(int i) :_id(i){
cout << "ctor.this = " << this << " id = " << _id << "\n";
}
~Foo(){
cout << "dtor.this = " << this << " id = " << _id << "\n";
}
//重载方法
static void* operator new(size_t size);
static void operator delete(void* pdead, size_t size);
static void* operator new[](size_t size);
static void operator delete[](void* pdead, size_t size);
private:
int _id;
long _data;
};
inline
void* Foo::operator new(size_t size){
Foo* p = (Foo*)malloc(size);
cout << "operator new(size_t size)" << endl;
return p;
}
inline
void Foo::operator delete(void* pdead, size_t size){
cout << "operator delete(void* pdead, size_t size)" << endl;
free(pdead);
}
inline
void* Foo::operator new[](size_t size){
Foo* p = (Foo*)malloc(size);
cout << "operator new[](size_t size)" << endl;
return p;
}
inline
void Foo::operator delete[](void* pdead, size_t size){
cout << "operator delete[](void* pdead, size_t size)" << endl;
free(pdead);
}
#endif
2)主程序
int _tmain(int argc, _TCHAR* argv[])
{
Foo* f = new Foo; //#1
delete f; //#2
cout << "\n";
Foo* f1 = new Foo[3]; //#3
delete[] f1; //#4
return 0;
}
/*输出结果:
operator new(size_t size) //#1
default ctor.this = 00D52C58 id = 0 //#1
dtor.this = 00D52C58 id = 0 //#2
operator delete(void* pdead, size_t size) //#2
operator new[](size_t size) //#3
default ctor.this = 00D51AF4 id = 0 //#3
default ctor.this = 00D51AFC id = 0 //#3
default ctor.this = 00D51B04 id = 0 //#3
dtor.this = 00D51B04 id = 0 //#4
dtor.this = 00D51AFC id = 0 //#4
dtor.this = 00D51AF4 id = 0 //#4
operator delete[](void* pdead, size_t size) //#4
*/
注意点:
a、主程序中#1,构造单一对象f时,会重载operator new()方法(与前面描述new的内存管理中分配内存相关),然后调用构造函数;
b、主程序中#2,当delete f时,会先调用析构函数,然后调用operator delete;
c、主程序中#3,构造数组对象f1时,会重载operator new[]方法,然后调用构造函数(会根据数组个数依次调用);
d、主程序中#4,析构数组对象f1时,会先调用析构函数(会根据数组个数依次调用,顺序与构造函数调用相反),然后调用operator delete[]。