1.重载new()/delete()
我们可以重载class member operator new(),写出很多版本,前提是每一版本的声明都必须有独特的参数列表,其中第一个参数必须是size_t,其与参数以new所指定的placement arguments为初值。出现于new(......)小括号内的便是所谓placement arguments。
Foo* pf = new (300, 'c') Foo;
我们可以重载class member operator delete(),写出很多版本。但它们绝不会被delete调用。只有当new所调用的ctor抛出exception,才会调用这些重载版本的operator delete()。它只可能这样被调用,主要用来归还未能完全创建成功的object所占用的memory。
2.示例
#include <iostream>
#include <stdlib.h>
using namespace std;
class Bad {
};
class Foo {
public:
Foo() {
cout << "Foo::Foo()" << endl;
}
Foo(int) {
cout << "Foo::Foo(int)" << endl;
throw Bad();
}
public:
//(1)这个就是一般的operator new()的重载
void* operator new(size_t size) {
return malloc(size);
}
//(2)这个就是标准库已提供的placement new() 的重载(的形式)
//(所以我也模拟stand placement new,就只是传回pointer)
void* operator new(size_t size, void* start) {
return start;
}
//(3)崭新的placement new
void* operator new(size_t size, long extra) {
return malloc(size + extra);
}
//(4)这又是一个placement new
void* operator new(size_t size, long extra, char init) {
return malloc(size + extra);
}
//(5)这又是一个placement new,但故意写错第一参数的type
//(那必须是size_t以符合正常的operato new)
//! void* operator new(long extra, char init) {
// return malloc(extra);
// }
//以下是搭配上述placement new 的各个所谓placement delete.
//当ctor发出异常,这儿对应的operator (placement) delete 就会被调用
//其用途是释放对应之placement new分配所得的memory.
//(1)
void operator delete(void*, size_t) {
cout << "void operator delete(void*, size_t)" << endl;
}
//(2)
void operator delete(void*, void*) {
cout << "void operator delete(void*, void*)" << endl;
}
//(3)
void operator delete(void*, long) {
cout << "void operator delete(void*, long)" << endl;
}
//(4)
void operator delete(void*, long , char ) {
cout << "void operator delete(void*, long , char )" << endl;
}
private:
int m_i;
};
int main() {
Foo start;
Foo* p1 = new Foo;
Foo* p2 = new(&start) Foo;
Foo* p3 = new(100) Foo;
Foo* p4 = new(100, 'a') Foo;
Foo* p5 = new(100) Foo(1);
Foo* p6 = new(100, 'a') Foo(1);
Foo* p7 = new(&start) Foo(1);
Foo* p8 = new Foo(1);
return 0;
}
3.basic_string 使用 new(extra)扩充申请量