以编程方式确定std :: string是否使用写时复制(COW)机制

4 c++ string algorithm copy-on-write

继续讨论这个问题后,我想知道如何使用本机C++以编程方式确定他们使用的std :: string实现是否利用了写时复制(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;
}
Run Code Online (Sandbox Code Playgroud)

问题是我似乎无法找到返回true的C++工具链.我的假设是否存在关于如何为std :: string实现COW的缺陷?

更新:基于kotlinski注释,我已经在函数中改变了对data()的writeble引用的使用,现在它似乎对某些实现返回"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;
}
Run Code Online (Sandbox Code Playgroud)

注意:根据N2668:"基本字符串的并发修改",在即将推出的C++ 0x标准中,COW选项将从basic_string中删除.感谢詹姆斯和贝尔达兹提出的建议.

Joh*_*ski 7

使用&s1[0]地址不是你想要的,[0]返回一个可写的引用,并将创建一个副本.

使用data()代替它,它返回一个const char*,你的测试可能会通过.