tags:

views:

173

answers:

3

Which "shared string" implementation for C++ would you recommend?

(Sorry if I missed a similar question. I had a look but could not find any)

+1  A: 

I would use the STL: std::string and std::wstring.

ONLY if you need something more fancy you could used the smart pointers to wrap your own implementation. These smart pointers are present in the new C++ STL or boost.

  • boost::shared_ptr for example if you use it inside a DLL
  • boost::intrusive_ptr works over DLL boundaries.

EDIT: Like remarked in the comments STL strings are not guaranteed to be immutable by nature. If you want them to be so, use the const specifier.

jdehaan
I guess by "shared string" the OP meant copy-on-write semantics, which the STL strings don't provide.
Lukáš Lalinský
OK he should use `const std::string` or `const std::wstring`, fully correct. Thanks.
jdehaan
@Lukáš: The STL string was designed to allow for copy-on-write (COW) implementations; and there are some STL implementations that actually use COW. It went a little bit out of favour, after Herb Sutter showed that naive COW can slow down things considerably (e.g. here http://gotw.ca/publications/optimizations.htm).
stephan
@stephan: true, but the problem is that you can't be sure that as you switch compilers/libraries the implementation will stay the same
rpg
High-level operations in a language always cost you something extra. With atomic integers the price is not too high, and you have less pain than with pointers, faster code than always making a copy.
Lukáš Lalinský
jdehaan
A: 

I recommend starting with the standard strings, std::string and std::wstring.

However, there's one caveat:

Neither of the two string classes enforces a particular encoding. If you want your application to behave well when dealing with other locales or other languages than English, you should either start with std::wstring, or use something like UTF8-CPP which lets you deal with UTF-8 strings.

As Joel Spolsky pointed out, you have to know which encoding your strings are in to handle them correctly.

Frerich Raabe
+1  A: 

std::(w)string can be shared, but this is not mandated by the standard. QString uses an atomic refcount for sharing.

rpg