一、new表达式工作步骤
使用new表达式时发生的三个步骤:
- 调用名为operator new的标准库函数,分配足够大的原始的未类型化的内存,
以保存指定类型的一个对象 - 运行该类型的一个构造函数初始化对象
- 返回指向新分配并构造的构造函数对象的指针
二、nedelete表达式工作步骤
使用delete表达式时发生的两个步骤:
4. 调用析构函数,回收对象所申请的资源
5. 调用名为operator delete的标准库函数释放该对象所用的内存
三、operator new和operator delete函数的重载版本
//operator new库函数
void * operator new(size_t);
void * operator new[](size_t);
//operator delete库函数
void operator delete(void *);
void operator delete[](void *);
void *operator new(size_t sz)
{
void * ret = malloc(sz);
//cout << "调用operator new" << endl;
return ret;
}
void operator delete(void * pointer)
{
free(pointer);
//cout << "调用operator delete" << endl;
}
只能创建栈对象
#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
#include "string.h"
#include <iostream>
//#include "stdio.h"
using std::cout;
using std::endl;
class Student
{
//public:
private:
void *operator new(size_t sz)
{
void * ret = malloc(sz);
cout << "调用operator new" << endl;
return ret;
}
public:
Student(int id,const char * name) //为什么这里要加const?
:_id(id),
_name(new char[strlen(name)+1])
{
strcpy(_name, name);
cout << "调用构造函数" << endl;
}
public:
//private:
~Student()
{
delete [] _name;
cout << "调用析构函数" << endl;
}
public:
//void destroy()
//{
// delete this;
//}
void operator delete(void * pointer)
{
free(pointer);
cout << "调用operator delete" << endl;
}
void print() const
{
cout << "_id:" << _id << endl;
cout << "_name:" << _name << endl;
}
private:
char* _name;
int _id;
};
//只能创建栈对象
//只能创建堆对象
int main()
{
//栈对象
Student stu_z(99, "lin");
stu_z.print();
//堆对象
//Student * stu_d = new Student(100, "KANG");
//stu_d->print();
////delete stu_d;
//stu_d->destroy();
system("pause");
return 0;
}
调用构造函数
_id:99
_name:lin
请按任意键继续. . .
调用析构函数
只能创建堆对象
#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
#include "string.h"
#include <iostream>
//#include "stdio.h"
using std::cout;
using std::endl;
class Student
{
public:
//private:
void *operator new(size_t sz)
{
void * ret = malloc(sz);
cout << "调用operator new" << endl;
return ret;
}
public:
Student(int id,const char * name) //为什么这里要加const?
:_id(id),
_name(new char[strlen(name)+1])
{
strcpy(_name, name);
cout << "调用构造函数" << endl;
}
//public:
private:
~Student()
{
delete [] _name;
cout << "调用析构函数" << endl;
}
public:
void destroy()
{
delete this;
}
void operator delete(void * pointer)
{
free(pointer);
cout << "调用operator delete" << endl;
}
void print() const
{
cout << "_id:" << _id << endl;
cout << "_name:" << _name << endl;
}
private:
char* _name;
int _id;
};
//只能创建堆对象
int main()
{
//栈对象
//Student stu_z(99, "lin");
//stu_z.print();
//堆对象
Student * stu_d = new Student(100, "KANG");
stu_d->print();
//delete stu_d;
stu_d->destroy();
system("pause");
return 0;
}
调用operator new
调用构造函数
_id:100
_name:KANG
调用析构函数
调用operator delete
请按任意键继续. . .