Hacker News new | ask | show | jobs
by jcelerier 1465 days ago
> The C++ API lets you take references into the string

> and then I scrawl "I AM Weasel" on top of my string using my reference and now your string was changed because it was COW.

I mean, that's the point of references... no ? If I wanted a different object I'd make a copy.

Like, even with just one string, without any CoW, your post makes it sound like you'd be surprised than if you had:

    void set_some_config(const char*);
    char* get_some_config();

    std::string s = "foo";
    set_some_config(&s[1]);
    s = "bar";
    get_some_config();
you'd get "ar" in get_some_config().
1 comments

> If I wanted a different object I'd make a copy.

In the explanation I posted, you do make a copy to get a different object "you use your C++ 98 copy constructor to get another string".

The problem happens because both strings share the same bytes to represent the text "IR Baboon big star of cartoon" as part of the COW optimisation. But my reference can scribble on this shared text.

I don't see how your get_some_config is similar at all. Notice that with C++ 11 strings, the copy constructor gives you a deep copy of that "IR Baboon" text and so my references can't smash your string.