跟进这一问题的讨论,我不知道如何来使用本机C ++编程方式确定与否的标准::字符串实现他们使用的是开发前景的的副本上写(COW)的
Following up on the discussion from this question, I was wondering how does one using native C++ determine programmatically whether or not the std::string implementation they are using utilizes Copy-On-Write (COW)
我有以下功能:
#include <iostream>
#include <string>
bool stdstring_supports_cow()
{
//make sure the string is longer than the size of potential
//implementation of small-string.
std::string s1 = "012345678901234567890123456789"
"012345678901234567890123456789"
"012345678901234567890123456789"
"012345678901234567890123456789"
"012345678901234567890123456789";
std::string s2 = s1;
std::string s3 = s2;
bool result1 = (&s1[0]) == (&s2[0]);
bool result2 = (&s1[0]) == (&s3[0]);
s2[0] = 'X';
bool result3 = (&s1[0]) != (&s2[0]);
bool result4 = (&s1[0]) == (&s3[0]);
s3[0] = 'X';
bool result5 = (&s1[0]) != (&s3[0]);
return result1 && result2 &&
result3 && result4 &&
result5;
}
int main()
{
if (stdstring_supports_cow())
std::cout << "std::string is COW." << std::endl;
else
std::cout << "std::string is NOT COW." << std::endl;
return 0;
}
现在的问题是,我似乎无法找到一个C ++工具链中,则返回true。有没有在我的假设一个缺陷有关如何牛是性病:: string的实现?
The problem is I can't seem to find a C++ tool chain where it returns true. Is there a flaw in my assumption about how COW is implemented for std::string?
更新:的基础上kotlinski的意见,我已经改变了使用writeble引用数据()中的功能,但现在看来,返回真的一些实施
Update: Based on kotlinski comments, I've changed the use of writeble references to data() in the function, it now seems to return "true" for some implementations.
bool stdstring_supports_cow()
{
//make sure the string is longer than the size of potential
//implementation of small-string.
std::string s1 = "012345678901234567890123456789"
"012345678901234567890123456789"
"012345678901234567890123456789"
"012345678901234567890123456789"
"012345678901234567890123456789";
std::string s2 = s1;
std::string s3 = s2;
bool result1 = s1.data() == s2.data();
bool result2 = s1.data() == s3.data();
s2[0] = 'X';
bool result3 = s1.data() != s2.data();
bool result4 = s1.data() == s3.data();
s3[0] = 'X';
bool result5 = s1.data() != s3.data();
return result1 && result2 &&
result3 && result4 &&
result5;
}
注:根据 N2668:并发修改以基本字符串,在即将到来的C ++ 0x标准,COW选项将被从basic_string的删除。由于詹姆斯和Beldaz为使这件事。
Note: According N2668: "Concurrency Modifications to Basic String", in the upcoming C++0x standard, COW option will be removed from basic_string. thanks to James and Beldaz for bringing that up.
使用&放大器; S1 [0]
带是不是你想要的联系地址, [0]
返回一个可写的参考,并创建一个副本。
Using &s1[0]
to take the adress is not what you want, [0]
returns a writable reference and will create a copy.
使用数据()代替,它返回一个const char *,并且您的测试可以通过。
Use data() instead, it returns a const char*, and your tests may pass.