Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 300
kravemir Avatar asked May 09 '12 15:05

kravemir


People also ask

Can new and delete operators be overloaded?

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.

How new and delete operators are used?

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.

Does the new operator allocate memory?

The new operator allocates memory to a variable.

How new and delete operators are used to allocate and de allocated the memory for a pointer give examples?

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.


2 Answers

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();
like image 90
Rafał Rawicki Avatar answered Nov 11 '22 21:11

Rafał Rawicki


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.

like image 43
Mankarse Avatar answered Nov 11 '22 23:11

Mankarse