1.new operator和delete operator
? ? //程序调用new operator做了下面两件事 ? ? //1.用操作符operator new开辟空间 ? ? //2.调用构造函数 ? ? //程序调用delete operator做了下面两件事 ? ? //1.调用析构函数 ? ? //2.operator delete释放p所指向的空间
#include <iostream>
using namespace std;
class Int {
private:
int data;
public:
Int(int i):data(i) {
cout << "构造对象"<< data << endl;
}
~Int() {
cout << "析构对象" << data << endl;
}
};
int main()
{
//Int i(10086);//这是静态开辟,编译器在编译的时候就知道这个类开辟多少空间
Int* p = new Int(10086);
delete p;
//程序调用new operator做了下面两件事
//1.用操作符operator new开辟空间
//2.调用构造函数
//程序调用delete operator做了下面两件事
//1.调用析构函数
//2.operator delete释放p所指向的空间
return 0;
}
2.operator new 和operator delete
#include <iostream>
using namespace std;
class Int {
private:
int data;
public:
Int(int i):data(i) {
cout << "构造对象"<< data << endl;
}
~Int() {
cout << "析构对象" << data << endl;
}
};
//====================================================================
void* operator new(size_t size)//size_t:unsigned int
{
cout << "开辟内存" << size <<endl;
void* p = malloc(size);
return p;
}
void operator delete(void* p)
{
cout << "释放内存" << p <<endl;
free(p);
}
//====================================================================
int main()
{
Int* q =new Int(1);//new操作符内部会自动计算Int类大小,然后把值赋值给size_t size
delete q;
//下面是实现过程
Int* p = (Int*)operator new(sizeof(Int));//开辟一个类大小的内存
new(p)Int(2);//把2放到开辟的空间中
p->~Int();//调用析构函数
operator delete (p);//释放内存空间
return 0;
}
//====================================================================
ee
.
|