Create new C++ object at specific memory address?

后端 未结 5 1341
悲&欢浪女
悲&欢浪女 2020-11-30 00:32

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?

5条回答
  •  甜味超标
    2020-11-30 01:00

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

提交回复
热议问题