为什么VC ++字符串不引用计数? [英] Why VC++ Strings are not reference counted?
问题描述
STL标准不需要从std :: string引用。但实际上大多数C ++
实现提供了引用计数的写时复制字符串,允许您将
string by value作为基本类型传递。这些实现(至少g ++)使用
原子操作使这些字符串无锁和线程安全。
轻松测试显示copy-on-write语义:
#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;
}
在使用非常数成员后,只打印两个地址。 / p>
我使用HP,GCC和Intel编译器测试了此代码,并得到类似的结果 - 字符串
用作写入时复制容器。
另一方面,VC ++ 2005清楚地显示每个字符串都完全复制。
为什么?
我知道VC ++ 6.0中有一个错误,它有非线程安全的
引用计数引起的随机程序崩溃。这是原因吗?他们只是
害怕使用ref计数,甚至是常见的做法吗?
感谢
我认为越来越多的 std :: string
实现将远离refcounting / copy-on-write,因为它通常是
请参阅Herb Sutter的文章未进行优化(在多线程世界中)。
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
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).
这篇关于为什么VC ++字符串不引用计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!