boost::interprocess - allocating objects using node_allocator
Hi,
I'd like to allocate objects directly in shared memory (not within STL-like
container) in the way like that:
struct X {
int a;
int b;
};
typedef boost::interprocess::node_allocator
Hi, alexmark wrote:
Hi, I'd like to allocate objects directly in shared memory (not within STL-like container) in the way like that:
You can use anonymous object construction for that (I've split the URL because it's too long): http://ice.prohosting.com/newfunk/boost/libs/interprocess/doc/ html/interprocess/managed_memory_segment_features.html #interprocess.managed_memory_segment_features.anonymous Example: X *ptr = sharm.construct<X>(anonymous_instance)(); //We can only destroy the anonymous object via pointer sharm.destroy_ptr(ptr); Or you need to use node_allocator because you think it's more optimized for your application?
struct X { int a; int b; };
typedef boost::interprocess::node_allocator
AllocType; int main (...) { // create shared memory managed_shared_memory sharm (create_only, "a_name", SOME_SIZE); // create allocator object AllocType alloc_object (sharm.get_segment_manager());
// allocate memory for object instance taking it from the allocator's pool X* p = detail::get_pointer(alloc_object.allocate(1)); // invoke the constructor alloc_object.construct(p, X());
// obtain the handle sharm.get_handle_from_address(p);
// now the handle is passed to another application to let it access the shared object // ....
}
Is it correct to do so? Will it work?
TYA
If you need the node allocator because of performance issues, take in care that once "alloc_object" is destroyed, you can't continue allocating objects and the allocator might release all the allocated memory, so you might end with memory corruption. An alternative is to allocate the allocator itself in shared memory: AllocType *ptr = sharm.construct<AllocType>("Alloc")(sharm.get_segment_manager()); This way you can find it from every part of the application searching it by name and the lifetime of the allocator will be the lifetime of the shared memory, unless you destroy it explicitly. But you should destroy all allocated object through this allocator before destroying the allocator itself. I hope this answers your question, Regards, Ion
participants (2)
-
alexmark
-
Ion Gaztañaga