在特定的内存地址创建新的 C++ 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1554774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:25:20  来源:igfitidea点击:

Create new C++ object at specific memory address?

c++memoryobjectpointerslocation

提问by Chris

Is it possible in C++ to create a new object at a specific memory location? I have a block of shared memory in which I would like to create an object. Is this possible?

在 C++ 中是否可以在特定的内存位置创建一个新对象?我有一块共享内存,我想在其中创建一个对象。这可能吗?

回答by D.Shawley

You want placement new(). It basically calls the constructor using a block of existing memory instead of allocating new memory from the heap.

你想要放置new()。它基本上使用现有内存块调用构造函数,而不是从堆中分配新内存。

Edit:make sure that you understand the note about being responsible for calling the destructor explicitly for objects created using placement new()before you use it!

编辑:在使用new()之前,请确保您了解有关负责为使用放置创建的对象显式调用析构函数的说明!

回答by dimba

Yes. You need to use placement variant of operator new(). For example:

是的。您需要使用运算符 new() 的放置变体。例如:

void *pData = ....; // memory segment having enough space to store A object
A *pA = new (pData) A;

Please note that placement new does not throw exception.

请注意,placement new 不会抛出异常。

回答by geva30

if you want to allocate a lot of fine-grained objects, the best approach will be to use placement new in conjunction with some sort of a ring buffer. otherwise, you will have to keep track of the pointers aside from the object pointers themselves.

如果你想分配很多细粒度的对象,最好的方法是将新放置与某种环形缓冲区结合使用。否则,除了对象指针本身之外,您还必须跟踪指针。

回答by PatrickvL

On Windows, MapViewOfFileExand VirtualAllocExallow one to specify a preferred virtual address. No guarantees though.

在 Windows 上,MapViewOfFileExVirtualAllocEx允许指定首选虚拟地址。虽然没有保证。

回答by AndruAllen

Assuming you have a pointer to the memory location you're wanting to place an object at, I believe one can cast the pointer to a new type and then place an object at the location of that pointer. This is a solution which doesn't require new().

假设您有一个指向要放置对象的内存位置的指针,我相信可以将指针转换为新类型,然后在该指针的位置放置一个对象。这是一个不需要 new() 的解决方案。

Given your memory:

鉴于你的记忆:

// you would use the pointer you have to your allocation of memory char* mem_start = new char[1024]; // Now we have 1024 bytes to play with

// you would use the pointer you have to your allocation of memory char* mem_start = new char[1024]; // Now we have 1024 bytes to play with

One can cast it to a given type:

可以将其强制转换为给定类型:

CustomType* object_ptr = (CustomType*) mem_start;

CustomType* object_ptr = (CustomType*) mem_start;

Lastly, you can construct an object there:

最后,您可以在那里构造一个对象:

*(object_ptr) = CustomType();

*(object_ptr) = CustomType();