Heim > Fragen und Antworten > Hauptteil
高洛峰2017-04-17 14:33:05
#include <iostream>
using namespace std;
class C {
public:
C(int i) : i(i) {
cout << "C constructor." << endl;
}
~C() {
cout << "C destructor." << endl;
}
// 此处声明为static或non-static均可,下同
/* static */ void *operator new(size_t size, void *p, const string& str) {
cout << "In our own operator new." << endl;
cout << str << endl;
if (!p) {
cout << "Hey man, are you aware what you are doing?" << endl;
return ::operator new(size); // !! 这是调用的全局的operator new(size_type)
}
return p;
}
/* static */ void operator delete(void *p) {
cout << "We should do nothing in operator delete." << endl;
// 如果取消下一行的注释,程序会在执行时crash
// ::operator delete(p); // !! 这里当然不能直接释放,你的内存可能是从operator new 参数中的buf分配来的,是栈上的内存
}
void f() {
cout << "hello object, i: " << i << endl;
}
private:
int i;
};
int main() {
char buf[sizeof(C)];
C *pc = new (buf, "Yeah, I'm crazy!") C(1024); // !! 当然是构造函数,再怎么也不能是数组,因为不是[]
// placement new 靠C(1024)构造函数来确定第一个参数的值
pc->f();
delete pc;
return 0;
}
参考:wikipedia-new