简体   繁体   中英

Create new C++ object at specific memory address?

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?

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

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!

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

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.

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.

On Windows, MapViewOfFileEx and VirtualAllocEx allow one to specify a preferred virtual address. No guarantees though.

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().

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

One can cast it to a given type:

CustomType* object_ptr = (CustomType*) mem_start;

Lastly, you can construct an object there:

*(object_ptr) = CustomType();

classname *objname = new (ptr) classname;```

You Can Do it by simple doing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM