std :: string是否仍在使用C ++ 11进行写时复制?

时间:2014-09-15 17:37:40

标签: c++ c++11

我的理解是,std::string的写时复制不再存在于C ++ 11中。

以下代码将证明这并非完全正确。

#include <string>
#include <iostream>

void Modify(std::string& s)
{
    if (!s.empty())
    {
         *const_cast<char*>(s.data()) = 'W';
    }
}

int main()
{
    std::string a = "Hello World";
    std::string b = a;  // Does not do a deep copy.

    Modify(a);

    std::cout << (a == b ? "Failed\n" : "Succeeded\n");

    return 0;
}

我不确定我在这里打破了什么规则。 无论如何抛弃const,为什么不能完成深层复制呢? 我知道可以用std::string b = a.c_str();强迫它,但这不是重点。

g ++(Ubuntu 4.8.2-19ubuntu1)4.8.2

0 个答案:

没有答案
相关问题