#include<cstring>
int main(){
string* a=new string("hello");
}
string* a=new string;实际上分为两步进行:
1.调用 void* operator new (size_t size),申请了size大小的内存,这个函数是可以重载的,但是第一个参数必须是size_t size;
2.调用构造函数,但是这一步我们是不能够修改的,但是我们却可以调用placement new来弥补这一点:
void* memory=operator new(sizeof(string));
string* a=new(memory)string("hello");
贴上一个利用重载operator new 和operator delete的方式实现的带有freeList的LinkList的一个结点:
struct Node{
Node(){
next=NULL;
}
Node(Elem v,Node<Elem>*n){
value=v;
next=n;
}
Elem value;
Node<Elem>* next;
//添加freeList
static Node<Elem>* freeList;
//分配内存
void* operator new(size_t size){
if(freeList==NULL){
return ::new Node;
}
Node<Elem>* it=freeList;
freeList=freeList->next;
return it;
}
void operator delete(void* ptr){
((Node<Elem>*)ptr)->next=freeList;
freeList=(Node<Elem>*)ptr;
}
};