"music4" <mu****@163.net> wrote in message news:<cg********@netnews.proxy.lucent.com>...
Greeting,
My platform is Solaris 2.8. My question is that if there is a simple way to
put a class object in share memory, so that multiple process can use this
object.
Thanks in advance!
Evan
The direct way is to allocate[1] a chunk of that shared memory for
your object, and then use placement new[2] to initialise the instance
in that memory.
The user-friendly-but-more-work way[3] is to write an operator new for
the class which takes as an extra argument the shared memory
'arena'[4] you want the object created in.
Footnotes:
[1] - you need some allocator for your shared memory which provides
the equivalent of new and delete functions for allocating/releasing
chunks of that shared segment. This might be entirely trivial if you
only ever want an array of one type of object, but it could be a
full-fledged heap implementation.
[2] - see the C++ FAQ or your favourite reference if you haven't used
this - it initialises an object in some raw memory.
[3] - this is only really friendlier if you're allocating these things
all over the place, and don't want to change the client code (much).
If you're using a factory function, there isn't much point doing this.
[4] - this could just be a pointer to the start of your shared memory
segment if your allocation routine is simple and well-known, or it
could be a pointer to an allocator object (see [1] again) which
provides a known allocation interface, where some allocator instance
is associated with a particular shm segment. See the C++ FAQ (again) -
section 11.14.
Caveats:
Note that if your objects aren't POD, you'll have to make sure that
all their subobjects allocate from the same shared memory segment.
For things like std::string, that means the typedef breaks, since you
need to pass std::basic_string a different allocator.
Also, none of this will work for objects having virtual functions,
because the vtable pointer will hold an address specific to the
process which created the object.