c++里new其实有三种含义:
- new operator
- operator new
- placement new
第一种new operator就是我们平时常用的:
1 2
|
class A*{}; A* a = new A();
|
这段代码其实做了了以下三部分工作:
1 2 3
|
A* a = (A*)malloc(sizeof(A)); // 分配内存 a->A::A(); // 调用构造函数 return a; // 返回指针
|
但有时候我们想自定义第一部分工作,于是就要重载operator new
1 2 3 4 5 6 7 8 9 10
|
class A { public: void* operator new(size_t size) { printf("operator new called/n"); return ::operator new(size); // return malloc(size); } };
|
如果想自定义第二部分工作,就要使用placement new
1 2 3 4 5 6 7 8 9
|
#include <new.h> class A {}; int main() { //A* a = new A(); A* p = (A*)malloc(sizeof(A)); new(p) A(); //相当于调用了构造函数 return 0; }
|
参考:
http://blog.csdn.net/songthin/article/details/1703966
近期评论