(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 <int>", "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 <int>", "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 <int>", "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 <int>", "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 <char>", "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 <int>", "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 <iostream>

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 <iostream>

//#include "TestException.h"

include <string>

include <iomanip>

include <ctime>

include <cstdlib>

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 <int>", "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 <char>", "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 <int>", "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;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容