STL standard do not require from std::string to be refcounted. But in fact most of C++ implementations provide refcounted, copy-on-write strings, allowing you passing string by value as a primitive type. Also these implementations (at least g++) use atomic operations making these string lock-free and thread safe.
Easy test shows copy-on-write semantics:
#include <iostream> #include <string> using namespace std; void foo(string s) { cout<<(void*)s.c_str()<<endl; string ss=s; cout<<(void*)ss.c_str()<<endl; char p=ss[0]; cout<<(void*)ss.c_str()<<endl; } int main() { string s="coocko"; cout<<(void*)s.c_str()<<endl; foo(s); cout<<(void*)s.c_str()<<endl; } Only two adresses are printed exactly after a non-constant member was used.
I tested this code using HP, GCC and Intel compiler and got similar results -- strings work as copy-on-write containers.
On the other hand, VC++ 2005 shows clearly that each string is fully copied.
Why?
I know that there was a bug in VC++6.0 that had non-thread-safe implementation of reference counting that caused random program craches. Is this the reason? They just afraid to use ref-counting any more even it is common practice? They prefer to not use ref-counting at all over fixing the issue?
Thanks