Create new C++ object at specific memory address?

后端 未结 5 1332
悲&欢浪女
悲&欢浪女 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:18

    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.

提交回复
热议问题