Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c++ - Why VC++ Strings are not reference counted?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think that more and more std::string implementations will move away from refcounting/copy-on-write as it is often a counter-optimization in multi-threaded code.

See Herb Sutter's article Optimizations That Aren't (In a Multithreaded World).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...