Sharing std::string across shared memory

2.2k Views Asked by At

I wish to share a std::string across processes using shared memory. However, I'm concerned about where the string object is allocated, on the stack, or heap, as this will affect the share.

Referring to this, MSDN Forum

...it says :

please note that in new STL (Visual Studio 2003 and 2005), the std::string class uses a combined variant of allocating strings. If the length is long then the string is allocated in heap area, but if is short, it is stored in a preallocated area of the class

I don't know how long the string might be...I'd not like to allocate any fixed memory to it.

All I was planning to do is...

wstring somestring;
somestring.sppend(someOtherString); //several times

I suppose wstring somestring[256] will be on the stack and so I can share that easily. But what if I don't wish to have a size allocated? And what would happen if the size grows beyond a threshold?

2

There are 2 best solutions below

2
On BEST ANSWER

I wish to share a std::string across processes using shared memory.

You cannot share non-POD types across process boundaries, especially types that may allocate memory internally. There is no guarantee that the other processes use the same version of the STL, if they use the STL at all. And even if they did, they would be using different memory managers.

You can instead allocate a fixed-length char[] array as the shared memory and copy the character content of the std::string into it.

I suppose wstring somestring[256] will be on the stack and so I can share that easily.

No, you cannot. somestring itself would be on the stack, but it is an array of std::wstring objects, and std::wstring cannot be shared.

But what if I don't wish to have a size allocated? And what would happen if the size grows beyond a threshold?

Shared memory is not dynamically sizable.

0
On

I endorse Remy Lebeau's answer: generally, don't even bother considering this.

A related line of inquiry might lead some readers to https://www.boost.org/doc/libs/1_57_0/doc/html/interprocess/allocators_containers.html and especially the STL containers in managed memory segments section. However, in the two projects where we even briefly discussed doing something like this, we instead did exactly what Remy suggests!