5

继这个问题的讨论之后,我想知道使用本机 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 提出这个问题。

4

2 回答 2

8

使用&s1[0]获取地址不是您想要的,[0]返回一个可写引用并创建一个副本。

改用 data(),它返回一个 const char*,你的测试可能会通过。

于 2010-12-21T04:08:15.630 回答
0

写时复制范式依赖于知道何时进行写操作。只要对象返回可写引用,就会发生这种情况。

如果您使用对字符串的 const 引用,则如果该类专门用于在返回对数据的 const 引用时禁用复制,则可以比较地址。

于 2010-12-21T04:14:27.867 回答