How can I use the `new` and` delete` operators in shared memory?

I want to share some objects between several programs using shared memory.

I found an example on this site . It has no object allocation, just direct addressing, but I want to create a structure or class in shared memory.

+4
source share
2 answers

Since the memory is already allocated, you want to use the new location :

void * ptr = shmat(shmid, 0, 0); // Handle errors MyClass * x = new (ptr) MyClass; 

Then a new instance of MyClass will be built in the memory marked with ptr .

When an object is not needed, you must manually call the destructor (without freeing memory).

 ptr->MyClass::~MyClass(); 
+7
source

An object can be created in any suitable matching repository using a new placement:

 void* storage = get_aligned_shared_memory(); T* object = new (storage) T(); 

However, you have considered using this library, for example Boost.Interprocess .

+6
source

Source: https://habr.com/ru/post/1411556/


All Articles