placement new和delete

注意,我们无法改变new和delete操作符。

但是我们可以重载来里面的operator new 和 operator delete 方法,这个方法是被new操作符调用的,调用之后获得地址,会继续用构造函数初始化。

另有一种operator new的方法叫作placement new,被禁止替换,(普通operator new可以替换,但一般不那么做),是两个参数,前面size_t被忽略,后面是地址,是直接用这个地址来调用构造函数。

 

调用的时候,是普通的new 后面加个括号和地址。

 

const size_t n = sizeof(string) * BUFFSIZE;

string *sbuf = static_cast<string *> (::operator new(n));

int size = 0;

 

void append(string buf[], int &size, const string &val) {

new (&buf[size++]) string(val);

}

 

void cleanup(string buf[], int size) {

  while (size) {

  buf[--size].~string();

  }

  ::operator delete(buf);

}

 

这种placement new的方式,广泛应用在大多数标准库容器的实现。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值