(Boolan)详解 C++ Operator new\delete、placement new\delete、Array new\delete

题目内容:

class Fruit{
int no;
double weight;
char key;
public:
void print() { }
virtual void process(){ }
};

class Apple: public Fruit{
int size;
char type;
public:
void save() { }
virtual void process(){ }
};

>
>
>为上周题目中的 Fruit和Apple 添加 构造函数与 析构函数, 并在构造函数与析构函数中打印控制台信息,
观察构造和析枸调用过程。然后为Apple类重载::operator new和 ::operator delete,在控制台打印信息,并观察调用结果。

#答案:
---
## 为了文章结构,我把代码放在文章后面,上面写的为代码片段,但为了方便查看运行结果,可以点击括号里面的链接(http://rextester.com/DOLN3287 ),进入后点击"run it"按钮就可以查看结果了
---
![父类和子类的关系](http://upload-images.jianshu.io/upload_images/5688965-16eec8112ecf6fa8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

#### 1.子类对象创建时:会先创建父类对象,再创建子类对象(之前讲的装快递的故事)
#### 2.子-类对象销毁时:会先销毁子类对象,再销毁父类对象(之前讲的拆快递的故事)
#### 3.子类的大小 = 父类成员属性的大小 + 虚函数指针(不存在为0Byte) + 子类成员属性的大小
#### 4.子类的内存中包括父类对象(由内存地址相同可知)
#### 5.placement new和placement delete最好能成对出现,除非保证创建对象时不会产生异常
#### 6.placement delete只会在new对象时抛出异常时才会调用,并且是成对调用(形参列表相同)。
#### 7.placement new创建对象如果不抛出异常,不会调用placement delete,而是调用operator new。
#### 8.不成对的placement new和placement delete的时候,如果产生了异常,则无法已经申请的释放空间,会造成内存泄漏。
---
## 为了文章结构,我把代码放在文章后面,上面写的为代码片段,但为了方便查看运行结果,可以点击括号里面的链接(http://rextester.com/DOLN3287 ),进入后点击"run it"按钮就可以查看结果了
---
- Fruit和Apple的UML关系图
![UML](http://upload-images.jianshu.io/upload_images/5688965-e9b8100020917b94.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

### 测试1:*** 子父类的构造函数、析构函数的调用情况 ***
- Fruit构造函数(节选)

.....
class Fruit {
int no;
double weight;
char key;
public:
Fruit(int n = 0, double w = 0., char k = '0');//Fruit类构造函数
~Fruit();//Fruit的析构函数
....
void print();
};
....
using namespace std;
inline Fruit::Fruit(int n, double w, char k) :no(n), weight(w), key(k) {
//如果为无参调用,随机生成Fruit中间的参数
if (n == 0 && w == 0. && k == '0') {
no = rand() % 100;
weight = rand() / RAND_MAX;
key = rand() % 26 + 97;
}
//Fruit的构造函数调用打印
printCalled("Fruit", "Fruit(int, double, char)");
}
.....
inline Fruit::~Fruit() {
//析构函数调用时,输出结果
cout << dec << "\nThe object Fruit(" << no << ", " << weight << ", " << key << ") has been deconstructed" << endl;
}
.....
inline void Fruit::print() {
//对象内容打印
cout << dec
<< "Fruit(" << no << ", " << weight << ", " << key << ")\n"
<< "size = " << sizeof(*this) << ", " << "address = 0x" << hex << this << endl;
}
.....


- Apple构造函数(节选)

class Apple : public Fruit {
private:
int size;
char type;
public:
Apple(int n = 0, double w = 0, char k = '0', int s = 0, char t = '0'); //构造函数
~Apple(); //析构函数
void print();
........
};
inline Apple::Apple(int n, double w, char k, int s, char t) :Fruit(n, w, k), size(s), type(t) {
//无参调用Apple的构造函数,会随机生成内容
if (n == 0 && w == 0. && k == '0' && s == 0 && t == '0') {
size = rand() % 100;
type = rand() % 26 + 97;
}
//构造函数被调用,打印信息
printCalled("Apple", "Apple(int, double, char, int, char)");
//打印对象信息
print();
}
....
inline Apple::~Apple() {
//析构函数
printCalled("Apple", "~Apple()");
}
......
inline void Apple::print() {
//打印Apple的对象信息
Fruit::print();
cout << dec << "\nApple (" << size << ", " << type << ")\n"
<< "size = " << sizeof(*this) << ", " << "address = 0x" << hex << this << endl;
}


- 测试部分代码

.....
inline void printCalled(const string scope, const string functionName) {
cout << "\n(" << scope << ") "<< functionName << " has been called\n";
}
const string s = "\n\n" + x * 50 + "\n\n";
int mian(){
.....
srand((unsigned) time(NULL));
//在栈里面创建对象的测试
cout << s << "\n" "在栈里面创建对象的测试" << endl;
Apple();//临时对象,生命周期仅在这一句,执行完就会弹出栈
.....
}
.....


- 结果
![在栈中创建对象](http://upload-images.jianshu.io/upload_images/5688965-8daca29432f24580.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 结论
1.子类对象创建时:会先创建父类对象,再创建子类对象(之前讲的装快递的故事)
2.子-类对象销毁时:会先销毁子类对象,再销毁父类对象(之前讲的拆快递的故事)
3.子类的大小 = 父类成员属性的大小 + 虚函数指针(不存在为0) + 子类成员属性的大小
4.子类的内存中包括父类对象(由内存地址相同可知)
---
### 测试二:测试operator new(无异常)
- Fruit代码

class Fruit {
int no;
double weight;
char key;
public:
Fruit(int n = 0, double w = 0., char k = '0');//Fruit类构造函数
~Fruit();//Fruit的析构函数

void* operator new(size_t size);    //覆写的Fruit的operator new

void operator delete(void* p);  //复写Fruit的operator delete
void operator delete(void* p, int type);

virtual void process() {   }
void print();

};
using namespace std;
inline Fruit::Fruit(int n, double w, char k) :no(n), weight(w), key(k) {
//如果为无参调用,随机生成Fruit中间的参数
if (n == 0 && w == 0. && k == '0') {
no = rand() % 100;
weight = rand() / RAND_MAX;
key = rand() % 26 + 97;
}
//Fruit的构造函数调用打印
printCalled("Fruit", "Fruit(int, double, char)");

//打印Fruit的对象情况
print();

}
inline Fruit::~Fruit() {
//析构函数调用时,输出结果
cout << dec << "\nThe object Fruit(" << no << ", " << weight << ", " << key << ") has been deconstructed" << endl;
}
inline void Fruit::print() {
//对象内容打印
cout << dec
<< "Fruit(" << no << ", " << weight << ", " << key << ")\n"
<< "size = " << sizeof(this) << ", " << "address = 0x" << hex << this << endl;
}
inline void
Fruit::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Fruit", "void* operator new(size_t)");
//this->print(); 错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的
return malloc(size);
}
inline void Fruit::operator delete(void* p) {
//operator delete被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void)");
//释放内存
free(p);
}
inline void Fruit::operator delete(void
p, int type) {
//placement delete 被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void*, int)");
//释放内存
free(p);
}


- Apple代码

class Apple : public Fruit {
private:
int size;
char type;
public:
Apple(int n = 0, double w = 0, char k = '0', int s = 0, char t = '0'); //构造函数
....
~Apple(); //析构函数
void* operator new(size_t size); //覆写的Apple的operator new
void operator delete(void* p); //覆写的Apple的operator delete

void print();
....

};
inline Apple::Apple(int n, double w, char k, int s, char t) :Fruit(n, w, k), size(s), type(t) {
//无参调用Apple的构造函数,会随机生成内容
if (n == 0 && w == 0. && k == '0' && s == 0 && t == '0') {
size = rand() % 100;
type = rand() % 26 + 97;
}
//构造函数被调用,打印信息
printCalled("Apple", "Apple(int, double, char, int, char)");
//打印对象信息
print();
}
inline Apple::~Apple() {
//析构函数
printCalled("Apple", "~Apple()");
}
inline void* Apple::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Apple", "void* operator new(size_t)");
//this->print(); 错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的
return malloc(size);
}
inline void Apple::operator delete(void* p) {
//operator delete
printCalled("Apple", "void operator delete(void*)");
free(p);
}

- 测试代码

int main()
{
srand((unsigned) time(NULL));
.......

//在堆里面创建对象的测试
cout << s << "\n" "通过普通的new,在堆里面创建对象的测试" << endl;
Apple* pa = new Apple();
delete pa;

}

- 运行结果
![operator new测试](http://upload-images.jianshu.io/upload_images/5688965-0282d9149974ef38.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 结论 
1.operator new 中的参数std::size_t的实参的大小实际为该对象所需的大小
2.调用子类的operator new / operator delete时,并不会调用父类的operate new 
/ operator delete
---
###测试三:operator new创建对象产生异常时的处理
- Fruit代码:

class Fruit {
int no;
double weight;
char key;
public:
Fruit(int n = 0, double w = 0., char k = '0');//Fruit类构造函数
~Fruit();//Fruit的析构函数
void* operator new(size_t size); //覆写的Fruit的operator new
void operator delete(void* p); //复写Fruit的operator delete
void operator delete(void* p, int type);
virtual void process() { }
void print();
};
using namespace std;
inline Fruit::Fruit(int n, double w, char k) :no(n), weight(w), key(k) {
//如果为无参调用,随机生成Fruit中间的参数
if (n == 0 && w == 0. && k == '0') {
no = rand() % 100;
weight = rand() / RAND_MAX;
key = rand() % 26 + 97;
}
//Fruit的构造函数调用打印
printCalled("Fruit", "Fruit(int, double, char)");
//打印Fruit的对象情况
print();
}
inline Fruit::~Fruit() {
//析构函数调用时,输出结果
cout << dec << "\nThe object Fruit(" << no << ", " << weight << ", " << key << ") has been deconstructed" << endl;
}
inline void Fruit::print() {
//对象内容打印
cout << dec
<< "Fruit(" << no << ", " << weight << ", " << key << ")\n"
<< "size = " << sizeof(this) << ", " << "address = 0x" << hex << this << endl;
}
inline void
Fruit::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Fruit", "void* operator new(size_t)");
//this->print(); 错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的
return malloc(size);
}
inline void Fruit::operator delete(void* p) {
//operator delete被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void)");
//释放内存
free(p);
}
inline void Fruit::operator delete(void
p, int type) {
//placement delete 被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void*, int)");
//释放内存
free(p);
}

- Apple代码:

class Apple : public Fruit {
private:
int size;
char type;
public:
Apple(char test); //会抛出异常的构造函数
~Apple(); //析构函数
void* operator new(size_t size); //覆写的Apple的operator new
void operator delete(void* p, int type); //覆写的placement delete
void print();
void save() { }
virtual void process() { }
.......
};
inline Apple::Apple(char test) {
//有参构造函数调用时打印信息
printCalled("Apple", "Apple(int)");
//抛出自定义异常
throw TestException();
}
inline Apple::~Apple() {
//析构函数
printCalled("Apple", "~Apple()");
}
inline void* Apple::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Apple", "void* operator new(size_t)");
//this->print(); 错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的
return malloc(size);
}
inline void Apple::operator delete(void* p) {
//operator delete
printCalled("Apple", "void operator delete(void*)");
free(p);
}

- 测试代码:

int main()
{
.....
Apple* pa1 = NULL;
//测试调用抛出异常的构造函数,重写了operator new,检测抛出异常后,会调用哪个delete
cout << s << "\n" "测试调用抛出异常的构造函数,重写了operator new,检测抛出异常后,会调用哪个delete " << endl;
try {
pa1 = new Apple('1');//
}
catch (TestException &e) {
cout << "\nexception catched\n" << e;
if(pa1)
delete pa1;
}
....
return 0;
}

- 运行结果:

![operator new的异常处理](http://upload-images.jianshu.io/upload_images/5688965-9ab8385849df21cf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 结论:
1.调用operator new创建对象时,如果创建对象时产生异常,处理异常时`delete p;`,会调用`operator delete;`来释放申请的内存。
2.自定义异常类对象,会在异常处理完成后被销毁
---
### 测试四:placement new处理异常时调用情况
- Fruit代码

class Fruit {
int no;
double weight;
char key;
public:
Fruit(int n = 0, double w = 0., char k = '0');//Fruit类构造函数
~Fruit();//Fruit的析构函数
void* operator new(size_t size); //覆写的Fruit的operator new
void operator delete(void* p); //复写Fruit的operator delete
void operator delete(void* p, int type);
virtual void process() { }
void print();
};
using namespace std;
inline Fruit::Fruit(int n, double w, char k) :no(n), weight(w), key(k) {
//如果为无参调用,随机生成Fruit中间的参数
if (n == 0 && w == 0. && k == '0') {
no = rand() % 100;
weight = rand() / RAND_MAX;
key = rand() % 26 + 97;
}
//Fruit的构造函数调用打印
printCalled("Fruit", "Fruit(int, double, char)");
//打印Fruit的对象情况
print();
}
inline Fruit::~Fruit() {
//析构函数调用时,输出结果
cout << dec << "\nThe object Fruit(" << no << ", " << weight << ", " << key << ") has been deconstructed" << endl;
}
inline void Fruit::print() {
//对象内容打印
cout << dec
<< "Fruit(" << no << ", " << weight << ", " << key << ")\n"
<< "size = " << sizeof(this) << ", " << "address = 0x" << hex << this << endl;
}
inline void
Fruit::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Fruit", "void* operator new(size_t)");
//this->print(); 错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的
return malloc(size);
}
inline void Fruit::operator delete(void* p) {
//operator delete被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void)");
//释放内存
free(p);
}
inline void Fruit::operator delete(void
p, int type) {
//placement delete 被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void*, int)");
//释放内存
free(p);
}

- Apple代码

class Apple : public Fruit {
private:
int size;
char type;
public:
Apple(int n = 0, double w = 0, char k = '0', int s = 0, char t = '0'); //构造函数
Apple(char test); //会抛出异常的构造函数
~Apple(); //析构函数

void* operator new(size_t size, int type);  //覆写的Apple的第一个placement new
void operator delete(void* p, int type);    //覆写的placement delete
void print();
void save() {   }
virtual void process() {   }

};
inline Apple::Apple(char test) {
//有参构造函数调用时打印信息
printCalled("Apple", "Apple(int)");
//抛出自定义异常
throw TestException();
}
inline Apple::~Apple() {
//析构函数
printCalled("Apple", "~Apple()");
}
inline void* Apple::operator new(size_t size, int type) {
//placement new
printCalled("Apple placement new ", "void* operator new(size_t, int)");
return malloc(size);
}
inline void Apple::operator delete(void* p, int type) {
//placement delete
//为和此处不可以使用this指针来释放内存空间呢?
//this->print();尝试
//如果使用this指针在该出调用,会报错,operator delete会自动转换为static的函数,所以形参列表中必须传入一个指针
printCalled("Apple placement delete ", "void operator delete(void, int)");
free(p);
}
inline void Apple::print() {
//打印Apple的对象信息
Fruit::print();
cout << dec << "\nApple (" << size << ", " << type << ")\n"
<< "size = " << sizeof(
this) << ", " << "address = 0x" << hex << this << endl;
}

- 测试代码

int main()
{
.....
Apple* pa2 = NULL;
//测试抛出异常的构造函数,重写并调用了placement new,检测抛出异常后,会调用哪个delete
cout << s << "\n" "测试抛出异常的构造函数,重写并调用了placement new,检测抛出异常后,会调用哪个delete" << endl;
try {
pa2 = new (1)Apple('1'); //调用了void* Apple::operator new(size_t, int)
}
catch (TestException &e) {
cout << "\nexception catched\n" << e;
if (pa2)
delete pa2;
}
....
return 0;
}

- 运行结果
![operator new的异常处理](http://upload-images.jianshu.io/upload_images/5688965-73c36459449b20ce.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
- 结论
1.new对象的时候,如果使用的时候用的是placement new,则处理异常时,会调用对应形参列表的placement delete
---
### 测试五:placement new 创建对象时,不产生异常的情况
- Fruit代码

class Fruit {
int no;
double weight;
char key;
public:
Fruit(int n = 0, double w = 0., char k = '0');//Fruit类构造函数
~Fruit();//Fruit的析构函数
void* operator new(size_t size); //覆写的Fruit的operator new
void operator delete(void* p); //复写Fruit的operator delete
void operator delete(void* p, int type);
virtual void process() { }
void print();
};
using namespace std;
inline Fruit::Fruit(int n, double w, char k) :no(n), weight(w), key(k) {
//如果为无参调用,随机生成Fruit中间的参数
if (n == 0 && w == 0. && k == '0') {
no = rand() % 100;
weight = rand() / RAND_MAX;
key = rand() % 26 + 97;
}
//Fruit的构造函数调用打印
printCalled("Fruit", "Fruit(int, double, char)");
//打印Fruit的对象情况
print();
}
inline Fruit::~Fruit() {
//析构函数调用时,输出结果
cout << dec << "\nThe object Fruit(" << no << ", " << weight << ", " << key << ") has been deconstructed" << endl;
}
inline void Fruit::print() {
//对象内容打印
cout << dec
<< "Fruit(" << no << ", " << weight << ", " << key << ")\n"
<< "size = " << sizeof(this) << ", " << "address = 0x" << hex << this << endl;
}
inline void
Fruit::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Fruit", "void* operator new(size_t)");
//this->print(); 错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的
return malloc(size);
}
inline void Fruit::operator delete(void* p) {
//operator delete被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void)");
//释放内存
free(p);
}
inline void Fruit::operator delete(void
p, int type) {
//placement delete 被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void*, int)");
//释放内存
free(p);
}

- Apple代码

class Apple : public Fruit {
private:
int size;
char type;
public:
Apple(int n = 0, double w = 0, char k = '0', int s = 0, char t = '0'); //构造函数
~Apple(); //析构函数
void* operator new(size_t size); //覆写的Apple的operator new
void* operator new(size_t size, int type); //覆写的Apple的第一个placement new

void operator delete(void* p);      //覆写的Apple的operator delete
void operator delete(void* p, int type);    //覆写的placement delete
void print();

.....
};
inline Apple::Apple(int n, double w, char k, int s, char t) :Fruit(n, w, k), size(s), type(t) {
//无参调用Apple的构造函数,会随机生成内容
if (n == 0 && w == 0. && k == '0' && s == 0 && t == '0') {
size = rand() % 100;
type = rand() % 26 + 97;
}
//构造函数被调用,打印信息
printCalled("Apple", "Apple(int, double, char, int, char)");
//打印对象信息
print();
}
inline Apple::~Apple() {
//析构函数
printCalled("Apple", "~Apple()");
}
inline void* Apple::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Apple", "void* operator new(size_t)");
//this->print(); 错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的
return malloc(size);
}
inline void* Apple::operator new(size_t size, int type) {
//placement new
printCalled("Apple placement new ", "void* operator new(size_t, int)");
return malloc(size);
}
inline void Apple::operator delete(void* p) {
//operator delete
printCalled("Apple", "void operator delete(void)");
free(p);
}
inline void Apple::operator delete(void
p, int type) {
//placement delete
//为和此处不可以使用this指针来释放内存空间呢?
//this->print();尝试
//如果使用this指针在该出调用,会报错,operator delete会自动转换为static的函数,所以形参列表中必须传入一个指针
printCalled("Apple placement delete ", "void operator delete(void, int)");
free(p);
}
inline void Apple::print() {
//打印Apple的对象信息
Fruit::print();
cout << dec << "\nApple (" << size << ", " << type << ")\n"
<< "size = " << sizeof(
this) << ", " << "address = 0x" << hex << this << endl;
}

- 测试代码

int main(){
//测试调用正常的构造函数的过程,使用的是重写的operator new,检测会调用那个delete
cout << s << "\n""测试调用正常的构造函数的过程,使用的是重写的operator new,检测会调用那个delete" << endl;
Apple* pa3 = new(1)Apple();
delete pa3;
return 0;
}

- 运行结果
![使用placement new创建对象不产生异常的结果](http://upload-images.jianshu.io/upload_images/5688965-b9f43aff7b4c1435.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 结论
1.调用placement new来创建对象时,如果没有产生异常,在delete时会调用operator delete
---
### 测试六:placement new 创建对象时,没有成对的placement delete的情况
- Fruit代码

class Fruit {
int no;
double weight;
char key;
public:
Fruit(int n = 0, double w = 0., char k = '0');//Fruit类构造函数
~Fruit();//Fruit的析构函数
void* operator new(size_t size); //覆写的Fruit的operator new
void operator delete(void* p); //复写Fruit的operator delete
void operator delete(void* p, int type);
virtual void process() { }
void print();
};
using namespace std;
inline Fruit::Fruit(int n, double w, char k) :no(n), weight(w), key(k) {
//如果为无参调用,随机生成Fruit中间的参数
if (n == 0 && w == 0. && k == '0') {
no = rand() % 100;
weight = rand() / RAND_MAX;
key = rand() % 26 + 97;
}
//Fruit的构造函数调用打印
printCalled("Fruit", "Fruit(int, double, char)");
//打印Fruit的对象情况
print();
}
inline Fruit::~Fruit() {
//析构函数调用时,输出结果
cout << dec << "\nThe object Fruit(" << no << ", " << weight << ", " << key << ") has been deconstructed" << endl;
}
inline void Fruit::print() {
//对象内容打印
cout << dec
<< "Fruit(" << no << ", " << weight << ", " << key << ")\n"
<< "size = " << sizeof(this) << ", " << "address = 0x" << hex << this << endl;
}
inline void
Fruit::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Fruit", "void* operator new(size_t)");
//this->print(); 错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的
return malloc(size);
}
inline void Fruit::operator delete(void* p) {
//operator delete被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void)");
//释放内存
free(p);
}
inline void Fruit::operator delete(void
p, int type) {
//placement delete 被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void*, int)");
//释放内存
free(p);
}

- Apple代码

class Apple : public Fruit {
private:
int size;
char type;
public:
Apple(char test); //会抛出异常的构造函数
~Apple(); //析构函数
void* operator new(size_t size, int type); //覆写的Apple的第一个placement new
void* operator new(size_t size, char type); //覆写的Apple的第二个placement new(这个一个没有配对的placement delete,为了方便测试内存泄漏情况)
void operator delete(void* p); //覆写的Apple的operator delete
void operator delete(void* p, int type); //覆写的placement delete
void print();
};
inline Apple::Apple(char test) {
//有参构造函数调用时打印信息
printCalled("Apple", "Apple(int)");
//抛出自定义异常
throw TestException();
}
inline Apple::~Apple() {
//析构函数
printCalled("Apple", "~Apple()");
}
inline void* Apple::operator new(size_t size, char type) {
//placement new
cout << "size_t = " << size << endl;
printCalled("Apple placement new ", "void* operator new(size_t, char)");
return malloc(size);
}
inline void Apple::operator delete(void* p) {
//operator delete
printCalled("Apple", "void operator delete(void)");
free(p);
}
inline void Apple::operator delete(void
p, int type) {
//placement delete
//为和此处不可以使用this指针来释放内存空间呢?
//this->print();尝试
//如果使用this指针在该出调用,会报错,operator delete会自动转换为static的函数,所以形参列表中必须传入一个指针
printCalled("Apple placement delete ", "void operator delete(void, int)");
free(p);
}
inline void Apple::print() {
//打印Apple的对象信息
Fruit::print();
cout << dec << "\nApple (" << size << ", " << type << ")\n"
<< "size = " << sizeof(
this) << ", " << "address = 0x" << hex << this << endl;
}

- 测试代码

int main(){

return 0;

}

- 运行结果
![不成对的placement new被调用还产生了异常](http://upload-images.jianshu.io/upload_images/5688965-7107f58840132473.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 结论
1.如果不存在成对的的placement new和placement delete,那么必须保证,** 创建对象时不会产生异常 **,否则就会造成内存泄漏。***如果存在产生异常的可能性,placement new和placement delete必须要成对出现。***
---
### 测试六:Array new测试
- Fruit代码

class Fruit {
int no;
double weight;
char key;
public:
Fruit(int n = 0, double w = 0., char k = '0');//Fruit类构造函数
~Fruit();//Fruit的析构函数
void* operator new(size_t size); //覆写的Fruit的operator new
void operator delete(void* p); //复写Fruit的operator delete
void operator delete(void* p, int type);
virtual void process() { }
void print();
};
using namespace std;
inline Fruit::Fruit(int n, double w, char k) :no(n), weight(w), key(k) {
//如果为无参调用,随机生成Fruit中间的参数
if (n == 0 && w == 0. && k == '0') {
no = rand() % 100;
weight = rand() / RAND_MAX;
key = rand() % 26 + 97;
}
//Fruit的构造函数调用打印
printCalled("Fruit", "Fruit(int, double, char)");
//打印Fruit的对象情况
print();
}
inline Fruit::~Fruit() {
//析构函数调用时,输出结果
cout << dec << "\nThe object Fruit(" << no << ", " << weight << ", " << key << ") has been deconstructed" << endl;
}
inline void Fruit::print() {
//对象内容打印
cout << dec
<< "Fruit(" << no << ", " << weight << ", " << key << ")\n"
<< "size = " << sizeof(this) << ", " << "address = 0x" << hex << this << endl;
}
inline void
Fruit::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Fruit", "void* operator new(size_t)");
//this->print(); 错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的
return malloc(size);
}
inline void Fruit::operator delete(void* p) {
//operator delete被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void)");
//释放内存
free(p);
}
inline void Fruit::operator delete(void
p, int type) {
//placement delete 被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void*, int)");
//释放内存
free(p);
}

- Apple代码

class Apple : public Fruit {
private:
int size;
char type;
public:
Apple(int n = 0, double w = 0, char k = '0', int s = 0, char t = '0'); //构造函数
Apple(char test); //会抛出异常的构造函数
~Apple(); //析构函数
void* operator new[](size_t size); //覆写的Apple的Array new
void operator delete[](void* p); //覆写的Array delete
void print();
.....
};
inline Apple::Apple(int n, double w, char k, int s, char t) :Fruit(n, w, k), size(s), type(t) {
//无参调用Apple的构造函数,会随机生成内容
if (n == 0 && w == 0. && k == '0' && s == 0 && t == '0') {
size = rand() % 100;
type = rand() % 26 + 97;
}
//构造函数被调用,打印信息
printCalled("Apple", "Apple(int, double, char, int, char)");
//打印对象信息
print();
}
inline Apple::~Apple() {
//析构函数
printCalled("Apple", "~Apple()");
}
inline void* Apple::operator new[](size_t size) {
//operator new[]
printCalled("Apple", "void* operator new(size_t)");
return malloc(size);
}
inline void Apple::operator delete[](void* p) {
//array delete
printCalled("Apple", "void operator delete");
free(p);
}
inline void Apple::print() {
//打印Apple的对象信息
Fruit::print();
cout << dec << "\nApple (" << size << ", " << type << ")\n"
<< "size = " << sizeof(*this) << ", " << "address = 0x" << hex << this << endl;
}

- 测试代码

int main(){
//数组测试
cout << s << "\n" "数组测试" << endl;
Apple* as1 = new Apple[2];
delete[] as1;
return 0;
}

- 运行结果
![Array new创建和销毁的情况](http://upload-images.jianshu.io/upload_images/5688965-39b53519113bacc2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 结论
1.对于数组创建,使用array new,会调用构造函数N次
2.对于数组的销毁,使用array delete,会调用其中对象的析构函数N次
---
- 全部代码

//************************
//************************
//*******自定义异常类******
//************************
//************************

ifndef TEST_EXCEPTION___

define TEST_EXCEPTION___

include

using namespace std;

//自定义异常
class TestException{
public:
//异常构造函数
TestException() {
cout << "TestException() has been called" << endl;
}
//异常的析构函数
~TestException() {
cout << "~TestException() has been called" << endl;
}

};

//打印异常信息
inline ostream& operator<< (ostream &o, const TestException &e) {
o << "TestException\n";
return o;
}

endif // !TEST_EXCEPTION___

//************************
//************************
//*******Fruit 和Apple****
//************************
//************************

ifndef FRUIT__EL_

define FRUIT__EL_

include

//#include "TestException.h"

include

include

include

include

string operator(string, const int);
inline void printCalled(const string, const string);
extern const string x = "
";

class Fruit {
int no;
double weight;
char key;
public:
Fruit(int n = 0, double w = 0., char k = '0');//Fruit类构造函数
~Fruit();//Fruit的析构函数

void* operator new(size_t size);

void operator delete(void* p);  //复写Fruit的operator delete
void operator delete(void* p, int type);

virtual void process() {   }
void print();

};

class Apple : public Fruit {
private:
int size;
char type;
public:
Apple(int n = 0, double w = 0, char k = '0', int s = 0, char t = '0'); //构造函数
Apple(char test); //会抛出异常的构造函数
~Apple(); //析构函数

void* operator new(size_t size);    //覆写的Apple的operator new
void* operator new[](size_t size);  //覆写的Apple的Array new
void* operator new(size_t size, int type);  //覆写的Apple的第一个placement new
void* operator new(size_t size, char type); //覆写的Apple的第二个placement new(这个一个没有配对的placement delete,为了方便测试内存泄漏情况)


void operator delete(void* p);      //覆写的Apple的operator delete
void operator delete(void* p, int type);    //覆写的placement delete

void operator delete[](void* p);    //覆写的Array delete

void print();
void save() {   }
virtual void process() {   }

};

using namespace std;
inline Fruit::Fruit(int n, double w, char k) :no(n), weight(w), key(k) {
//如果为无参调用,随机生成Fruit中间的参数
if (n == 0 && w == 0. && k == '0') {
no = rand() % 100;
weight = rand() / RAND_MAX;
key = rand() % 26 + 97;
}
//Fruit的构造函数调用打印
printCalled("Fruit", "Fruit(int, double, char)");

}
inline Fruit::~Fruit() {
//析构函数调用时,输出结果
cout << dec << "\nThe object Fruit(" << no << ", " << weight << ", " << key << ") has been deconstructed" << endl;
}

inline void Fruit::print() {
//对象内容打印
cout << dec
<< "Fruit(" << no << ", " << weight << ", " << key << ")\n"
<< "size = " << sizeof(*this) << ", " << "address = 0x" << hex << this << endl;
}

inline void* Fruit::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Apple", "void* operator new(size_t)");

//this->print();    错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的

return malloc(size);

}

inline void Fruit::operator delete(void* p) {
//operator delete被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void*)");
//释放内存
free(p);
}

inline void Fruit::operator delete(void* p, int type) {
//placement delete 被调用时打印调用信息
printCalled("Fruit", "void* operator delete(void*, int)");
//释放内存
free(p);
}

inline Apple::Apple(int n, double w, char k, int s, char t) :Fruit(n, w, k), size(s), type(t) {
//无参调用Apple的构造函数,会随机生成内容
if (n == 0 && w == 0. && k == '0' && s == 0 && t == '0') {
size = rand() % 100;
type = rand() % 26 + 97;
}
//构造函数被调用,打印信息
printCalled("Apple", "Apple(int, double, char, int, char)");
//打印对象信息
print();
}

inline Apple::Apple(char test) {
//有参构造函数调用时打印信息
printCalled("Apple", "Apple(int)");
//抛出自定义异常
throw TestException();
}

inline Apple::~Apple() {
//析构函数
printCalled("Apple", "~Apple()");
}

inline void* Apple::operator new(size_t size) {
//operator new
cout << "size_t = " << size << endl;
printCalled("Apple", "void* operator new(size_t)");

//this->print();    错误提示:static不能调用non-static
//如果使用this指针在该处调用,会报错,operator new会自动转换为static的函数,仅用于分配空间,不会修改对象的内容
//换而言之,此时对象还尚未创建完成,仅仅分配了内存空间,所以this指针存在也是不可能的

return malloc(size);

}

inline void* Apple::operator new[](size_t size) {
//operator new[]
printCalled("Apple", "void* operator new");
return malloc(size);
}

inline void* Apple::operator new(size_t size, int type) {
//placement new
printCalled("Apple placement new ", "void* operator new(size_t, int)");
return malloc(size);
}

inline void* Apple::operator new(size_t size, char type) {
//placement new
cout << "size_t = " << size << endl;
printCalled("Apple placement new ", "void* operator new(size_t, char)");

return malloc(size);

}

inline void Apple::operator delete(void* p) {
//operator delete
printCalled("Apple", "void operator delete(void*)");
free(p);
}

inline void Apple::operator delete(void* p, int type) {
//placement delete
//为和此处不可以使用this指针来释放内存空间呢?
//this->print();尝试
//如果使用this指针在该出调用,会报错,operator delete会自动转换为static的函数,所以形参列表中必须传入一个指针
printCalled("Apple placement delete ", "void operator delete(void*, int)");
free(p);
}

inline void Apple::operator delete[](void* p) {
//array delete
printCalled("Apple", "void operator delete");
free(p);
}

inline void Apple::print() {
//打印Apple的对象信息
Fruit::print();
cout << dec << "\nApple (" << size << ", " << type << ")\n"
<< "size = " << sizeof(*this) << ", " << "address = 0x" << hex << this << endl;
}

inline string operator*(string content,const int count) {
string c = content;
for (int i = 0; i < count; i++) {
content += c;
}
return content;
}

inline void printCalled(const string scope, const string functionName) {
cout << "\n(" << scope << ") "<< functionName << " has been called\n";
}

endif // !FRUIT__EL_

const string s = "\n\n" + x * 50 + "\n\n";
int main()
{
srand((unsigned) time(NULL));
//在栈里面创建对象的测试
cout << s << "\n" "在栈里面创建对象的测试" << endl;
Apple();//临时对象,生命周期仅在这一句,执行完就会弹出栈

cout << x * 50 << "\n\n\n";

//在堆里面创建对象的测试
cout << s << "\n" "通过普通的new,在堆里面创建对象的测试" << endl;
Apple* pa = new Apple();
delete pa;  

Apple* pa1 = NULL, *pa2 = NULL;

//测试调用抛出异常的构造函数,重写了operator new,检测抛出异常后,会调用哪个delete 
cout << s << "\n" "测试调用抛出异常的构造函数,重写了operator new,检测抛出异常后,会调用哪个delete " << endl;
try {
    pa1 = new Apple('1');
}
catch (TestException &e) {
    cout << "\nexception catched\n" << e;
    if(pa1)
        delete pa1;
}

//测试抛出异常的构造函数,重写并调用了placement new,检测抛出异常后,会调用哪个delete
cout << s << "\n" "测试抛出异常的构造函数,重写并调用了placement new,检测抛出异常后,会调用哪个delete" << endl;
try {
    pa2 = new (1)Apple('1');
}
catch (TestException &e) {
    cout << "\nexception catched\n" << e;
    if (pa2)
        delete pa2;
}

//测试调用一个不成对的placement new,会调用那个delete
cout << s << "\n" "测试调用一个不成对的placement new,检测抛出异常后,会调用哪个delete" << endl;
try {
    pa2 = new ('1')Apple('1');  
}
catch (TestException &e) {
    cout << "\nexception catched\n" << e;
    if (pa2)
        delete pa2;
}

//测试调用正常的构造函数的过程,使用的是重写的operator new,检测会调用那个delete
cout << s << "\n""测试调用正常的构造函数的过程,使用的是重写的operator new,检测会调用那个delete" << endl;
Apple* pa3 = new(1)Apple();
delete pa3;

//数组测试
cout << s << "\n" "数组测试" << endl;
Apple* as1 = new Apple[2];
delete[] as1;



return 0;

}

你可能感兴趣的:((Boolan)详解 C++ Operator new\delete、placement new\delete、Array new\delete)