[英]Create objects in pre-allocated memory
We can use placement new to create an object in pre-allocated memory. 我们可以使用placement new在预先分配的内存中创建一个对象。
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
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?
首先在缓冲区中创建一个数组,然后在数组的元素槽中创建每个对象?
The two objects are both created at the same memory location, namely buf
. 这两个对象都在同一个内存位置创建,即
buf
。 This is undefined behaviour (unless the objects are POD). 这是未定义的行为 (除非对象是POD)。
If you want to allocate several objects, you have to increment the pointer, eg buf + n * sizeof(MyObject)
, but beware of alignment issues 如果要分配多个对象,则必须增加指针,例如
buf + n * sizeof(MyObject)
,但要注意对齐问题
Also don't forget to call destructors when you're done. 完成后别忘了打电话给析构函数。
The following line of code: 以下代码行:
string *p = new(adr) MyObject();
will create a MyObject object at the address adr. 将在地址adr处创建一个MyObject对象。 Then next time you create another object, you will know that the memory at adr is being used by the first object, so your next object will have to be created at
adr + sizeof(MyObject)
: 然后,下次创建另一个对象时,您将知道第一个对象正在使用adr的内存,因此必须在
adr + sizeof(MyObject)
创建下一个对象:
string *q = new(adr + sizeof(MyObject)) MyObject();
The point of pre-allocated memory is so that you aren't allocating at runtime, which is pretty slow. 预分配内存的要点是你没有在运行时分配,这非常慢。 You do one big allocation at the beginning of the loop/program and then you just have to use chunks of that allocation.
你在循环/程序的开头做了一个大的分配,然后你只需要使用那个分配的块。 The down side is that you have to manage your own memory which means you have to figure out where to put your objects which gets tricky when your memory pool gets fragmented!
缺点是你必须管理你自己的内存,这意味着当你的内存池碎片化时你必须弄清楚你的对象放在哪里变得棘手!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.