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

标签 c++ algorithm string copy-on-write

根据这个 question 的讨论,我想知道使用 native 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 提出这个问题。

最佳答案

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

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

关于c++ - 以编程方式确定 std::string 是否使用写时复制 (COW) 机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4496150/

相关文章:

C++ 使用 (void * caller obj) 参数访问类私有(private)属性友元函数

c++ - 替换 shared_ptr<T> 中对对象的所有引用

algorithm - 内容相关搜索:对购物产品进行分类

java - 将字符串转换为 Int

c++ - 在 C++ 中存储字符串时,char* 和 char 有什么区别?

regex - Grep invert 字符串匹配,而不是行匹配

c++ - 在 C++ 中选择重载模板函数时的优先级

algorithm - 到给定顶点的所有最短路径

algorithm - 实现智能列表

c++ - DirectShow 视频在音频引脚渲染数据时播放速度过快