C++ operator new placement new
一、整体代码 01.cpp
#include<iostream> #include <stdlib.h> usingnamespace std; class Test { public: Test(int n) : n_(n) { cout<<"Test(int n) : n_(n)"<<endl; } Test(const Test& other) { cout<<"Test(const Test& other)"<<endl; } ~Test() { cout<<"~Test()"<<endl; } void *operator new(size_t size)//普通情况调用,标注为0 { cout<<"void* operator new(size_t size)"<<endl; void* p = malloc(size); return p; } void operator delete(void* p) { cout<<"void operator delete(void* p)"<<endl; free(p); } void operator delete(void* p, size_t size)//如果上面那个和这个delete都有,那么调用上面的。 { cout<<"void operator delete(void* p, size_t size)"<<endl; free(p); } void* operator new(size_t size, constchar* file, long line)//另一种情况调用,标注为1 { cout<<file<<":"<<line<<endl; void* p = malloc(size); return p; } void operator delete(void* p, constchar* file, long line) { cout<<file<<":"<<line<<endl; free(p); } void* operator new(size_t size, void* p)//另一种情况调用,标注为2 { cout<<"run"<<endl; return p; } void operator delete(void*, void*) { cout<<"destory"<<endl; } int n_; }; void* operator new[](size_t size)//全局非Test类调用此方法,标注为3 { cout<<"global void* operator new[](size_t size)"<<endl; void* p = malloc(size); return p; } void operator delete[](void* p) { cout<<"global void operator delete[](void* p)"<<endl; free(p); } int main(void) { Test* p1 =new Test(100); // new operator = operator new + 构造函数的调用 调用标注0 delete p1; //delete = 析构函数的调用+operator delete char* str =new char[100]; //调用标注3 delete[] str; char chunk[10]; Test* p2 =new (chunk) Test(200); //operator new(size_t, void *_Where)+构造函数的调用 // placement new,不分配内存+ 构造函数的调用 //调用标注2 cout<<p2->n_<<endl; p2->~Test(); // 显式调用析构函数,因为没有分配内存,所以直接调用析构函数 return0; }
二、解释
1、 Test* p1 = new Test(100);
delete p1;
结果如下:
void* operator new(size_t size)
Test(int n) : n_(n)
~Test()
void operator delete(void* p)
2、char * str = new char[100];
delete[] str;
结果如下:
global void* operator new[](size_t size)
global void operator delete[](void* p)
3、char chunk[10];
Test* p2 =new (chunk) Test(200);
cout<<p2->n_<<endl;
p2->~Test()
结果如下:
run
Test(int n) : n_(n)
200
~Test()
补充:软件开发 , C++ ,