在一篇博客上看到,下面的这段代码:
#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);
}
return p;
}
/* static */ void operator delete(void *p) {
cout << "We should do nothing in operator delete." << endl;
// 如果取消下一行的注释,程序会在执行时crash
// ::operator delete(p);
}
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);
pc->f();
delete pc;
return 0;
}
有点困惑:
1.其中类里面的operator new()
函数里面,调用了一个全局的::operator new()
,这个调用的operator new(size)
是placement new
还是default new
?
2.在main()
函数中, C *pc = new (buf, "Yeah, I'm crazy!") C(1024);
,这一句后面的C(1024)
是调用的C的构造函数
,还是说有1024个C
?还有为什么这里的new
里面的参数只有两个?
参考:wikipedia-new