GNU STL string: is copy-on-write involved here?

淺唱寂寞╮ 提交于 2019-11-30 06:46:35

C++ doesn't distinguish between the operator[] for reading and writing, but only the operator[] for const object and mutable (non-const) object. Since a_copy is mutable, the mutable operator[] will be chosen, which forces the copying because that operator returns a (mutable) reference.

If efficiency is a concern, you could cast the a_copy to a const string to force the const version of operator[] to be used, which won't make a copy of the internal buffer.

char f = static_cast<const string>(a_copy)[99];

The C++ standard doesn't prohibit or mandate copy-on-write or any other implementation details for std::string. So long as the semantics and complexity requirements are met an implementation may choose whatever implementation strategy it likes.

Note that operator[] on a non-const string is effectively a "write" operation as it returns a reference that can be used to modify the string at any point up to the next operation that mutates the the string. No copies should be affected by such a modification.

Have you tried profiling one of these two?

const string a_copy = basestr;
a_copy[99];

Or

string a_copy = basestr;
const std::string& a_copy_ref = a_copy;
a_copy_ref[99];

Try this code:

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

template<typename T>
void dump(std::ostream & ostr, const T & val)
{
    const unsigned char * cp = reinterpret_cast<const unsigned char *>(&val);
    for(int i=0; i<sizeof(T); i++)
        ostr
            << setw(2) << setfill('0') << hex << (int)cp[i] << ' ';
    ostr << endl;
}

int main(void) {
    string a = "hello world";
    string b = a;
    dump(cout,a);
    dump(cout,b);

    char c = b[0];

    dump(cout,a);
    dump(cout,b);
}

On GCC, this is the output I get:

3c 10 51 00
3c 10 51 00
3c 10 51 00
5c 10 51 00

Which would seem to indicate that yes, they are copy on read in this case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!