创建pre-分配的内存对象 [英] Create objects in pre-allocated memory

查看:147
本文介绍了创建pre-分配的内存对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用新的位置来创建pre-分配的内存中的对象。

We can use placement new to create an object in pre-allocated memory.

让我们看看下面的例子:

Let's consider the following example:

char *buf  = new char[1000];   //pre-allocated buffer
string *p = new (buf) MyObject();  //placement new 
string *q = new (buf) MyObject();  //placement new

我已经创建了pre-分配的缓冲区两个对象。是两个物体随机生成缓冲区内或连续的内存块产生的?如果我们继续在缓冲区中创造更多的对象,并希望它们被保存在连续的内存块,我们该怎么办?首先创建在缓冲器阵列,然后在阵列的元件缝隙创建每个对象

I've created two objects in the pre-allocated buffer. Are the two objects created randomly within the buffer or created in contiguous memory blocks? If we keep creating more objects in the buffer and want them to be stored in contiguous memory blocks, what should we do? Create an array in the buffer first and then create each object in the element slots of the array?

推荐答案

都在相同的内存位置创建的两个对象,即 BUF 。这就是未定义行为(除非对象是POD)。

The two objects are both created at the same memory location, namely buf. This is undefined behaviour (unless the objects are POD).

如果你想分配几个对象,你必须增加指针,例如 BUF + N * sizeof的(为MyObject),但要注意的对齐问题

If you want to allocate several objects, you have to increment the pointer, e.g. buf + n * sizeof(MyObject), but beware of alignment issues

另外,不要忘记调用析构函数时,就大功告成了。

Also don't forget to call destructors when you're done.

这篇关于创建pre-分配的内存对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆