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.
New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.
Memory that is dynamically allocated using the new operator can be freed using the delete operator. The delete operator calls the operator delete function, which frees memory back to the available pool. Using the delete operator also causes the class destructor (if one exists) to be called.
The new operator allocates memory to a variable.
Examples: delete p; delete q; To free the dynamically allocated array pointed by pointer variable, use the following form of delete: // Release block of memory // pointed by pointer-variable delete[] pointer-variable; Example: // It will free the entire array // pointed by p.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With