Why is COW std::string optimization still enabled in GCC 5.1?

According to GCC 5 release changes page (https://gcc.gnu.org/gcc-5/changes.html):

A new implementation of std::string is enabled by default, using the small string optimization instead of copy-on-write reference counting

I decided to check it and wrote a simple program:

int main()
    std::string x{"blah"};
    std::string y = x;
    printf("0x%Xn", x.c_str());
    printf("0x%Xn", y.c_str());
    x[0] = 'c';
    printf("0x%Xn", x.c_str());
    printf("0x%Xn", y.c_str());

And the result is:


Notice that the x.c_str() pointer changes after x[0] = ‘c’. This means that the internal buffer is copied upon write. So it seems that COW is still in work. Why?

I use g++ 5.1.0 on Ubuntu.

Source: c++

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.