继这个问题的讨论之后,我想知道使用本机 C++ 的人如何以编程方式确定他们正在使用的 std::string 实现是否使用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;
}
问题是我似乎找不到返回 true 的 C++ 工具链。我对如何为 std::string 实现 COW 的假设是否存在缺陷?
更新:根据 kotlinski 的评论,我改变了函数中对 data() 的可写引用的使用,现在对于某些实现,它似乎返回“true”。
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: "Concurrency Modifications to Basic String",在即将发布的 C++0x 标准中,COW 选项将从 basic_string 中删除。感谢 James 和 Beldaz 提出这个问题。