Shared string in C++?
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开发者_开发知识库)
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 DLLboost::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.
std::(w)string can be shared, but this is not mandated by the standard. QString uses an atomic refcount for sharing.
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.
精彩评论