About placement new operator

本文介绍如何使用placement new操作在已分配的内存空间中创建对象,节省内存资源并避免重新分配。同时解释了使用placement new时构造函数的调用以及额外内存的分配情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

We can use placement new operator to allocate an object on appointed memory.

For example:

char* buf = new char[1000];

Object* pobj = new(buffer)Object();

The object will use the buf space instead of allocate a new memory space. But the constructor will still be called.

 

BTW:

If you create NUM of objects by calling new[] operator. It will allocate sizeof(object) * NUM+ sizeof(int) bytes memories.

NUM will be strored at the begin of allocated memories. That's why the extra 4 byted allocated.

When delete[] is called. The destructor will be called NUM times(If you manually change this NUM, you'll see it).

If a class has no destructor, the extra 4 bytes space won't be allocated.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值