Art*_*yom 13 c++ string reference-counting copy-on-write visual-c++
STL标准不要求从std :: string中重新计算.但事实上,大多数C++实现都提供了refcounted,copy-on-write字符串,允许您将值作为基本类型传递.此外,这些实现(至少g ++)使用原子操作使这些字符串无锁和线程安全.
简单的测试显示了写时复制语义:
#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;
}
Run Code Online (Sandbox Code Playgroud)
在使用非常数成员后,只有两个地址完全打印.
我使用HP,GCC和Intel编译器测试了这段代码,得到了类似的结果 - 字符串可以作为写时复制容器.
另一方面,VC++ 2005清楚地表明每个字符串都是完全复制的.
为什么?
我知道VC++ 6.0中存在一个错误,它具有非线程安全的引用计数实现,导致随机程序崩溃.这是什么原因?他们只是害怕再使用ref-count,即使这是常见的做法?他们宁愿不使用重新计算来解决问题吗?
谢谢
Mic*_*urr 22
我认为越来越多的std::string实现将远离refcounting/copy-on-write,因为它通常是多线程代码中的反优化.
请参阅Herb Sutter的文章"不优化(在多线程世界中)".
Mar*_*ork 11
STL实际要求如果使用引用计数,则语义与非引用计数版本相同.这对于一般情况来说并非无足轻重.(这就是为什么你不应该写你的字符串类).
由于以下情况:
std::string x("This is a string");
char& x5 = x[5];
std::string y(x);
x5 = '*';
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅:http://www.sgi.com/tech/stl/string_discussion.html
正如Martin&Michael所说,Copy On Write(COW)通常比它的价值更麻烦,为了进一步阅读,请参阅Kelvin Henney关于Mad COW Disease的优秀文章,我相信Andrei Alexandrescu表示小字符串优化表现更好在许多应用程序中(但我找不到文章).
小字符串优化是使字符串对象更大并避免小字符串堆分配的地方.玩具实现看起来像这样:
class string {
char *begin_, *end_, *capacity_;
char buff_[64]; // pick optimal size (or template argument)
public:
string(const char* str)
{
size_t len = strlen(str);
if (len < sizeof(buff_))
{
strcpy(buff_, str);
begin_ = buff_;
capacity_ = buff_ + sizeof(buff_);
}
else
{
begin_ = strdup(str);
capacity_ = begin_ + len;
}
end_ = begin_+len;
}
~string()
{
if (begin_ != buff_)
free(begin_); // strdup requires free
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
小智 5
也许Microsoft确定字符串复制不是一个大问题,因为几乎所有的C++代码都尽可能使用传递引用.保持引用计数有空间和时间的开销(忽略锁定),也许他们认为不值得付费.
或者可能不是.如果您对此感兴趣,则应分析应用程序以确定字符串复制是否是主要开销,以及是否切换到其他字符串实现.