简体   繁体   中英

How can i use operators `new` and `delete` within shared memory?

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

I've found example at this site . It doesn't have any allocation of object, just direct addressing, but i want to create struct or class in shared memory.

Because the memory is already allocated you want to use placement new :

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

Then, the new instance of MyClass will be constructed in memory pointed by ptr .

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

ptr->MyClass::~MyClass();

An object can be created in any suitable aligned storage using placement new:

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

That said — have you considered using a library such as Boost.Interprocess for 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