gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:40:15 31 4
gpt4 key购买 nike

根据这个 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com