关于C++中new的一些理解

#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;
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值