C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Appending a string to itself

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Fri, 21 Jul 2023 20:36:18 +0100
On Fri, 21 Jul 2023, 18:16 Arthur O'Dwyer via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

> On Fri, Jul 21, 2023 at 12:59 PM Jerry Coffin via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>> There's a corner case for which the current specification of
>> `std::string::append` will frequently lead to undefined behavior.
>>
>> Consider something like:
>>
>> ```cpp
>> std::strings = "A long enough string that two copies of it probably won't
>> fit into the currently allocated storage";
>> s.append(s);
>> ```
>>
>
> Even more natural:
> s += s;
> which is equivalent to
> s.append(s)
> which is equivalent to
> s.append(s.data(), s.size())
> which has the following effects ([string.append]/8
> <https://eel.is/c++draft/string.modifiers#string.append-8>):
> > Appends a copy of the range [s, s + n) to the string.
>
> However — it is not clear to me that this wording gives the implementation
> permission to append *anything other than* [s, s+n) to the string in the
> case that the appending operation itself causes [s, s+n) to become
> invalidated.
>

This is absolutely required to work. The string can detect that the
argument aliases its current content and deal with it.

It also has to work for s.insert(pos1, s, pos2, n) and s.replace(pos1, n1,
s, pos2, n2) which is trickier, but has to work.

The only time the implementation doesn't have to deal with this is if the
string parameters is an rvalue reference, in which case it can assume no
aliasing.




> In fact, I've been here before:
> https://quuxplusone.github.io/blog/2021/04/17/pathological-string-appends/
>
> Are you actually seeing some real-world `std::string` implementation
> misbehave? If so, I strongly recommend filing a bug with that vendor. They
> almost certainly already believe that they have to implement the behavior
> you expected, and so they'll treat it as a real bug (even if a hard-to-fix
> one).
>
> Cheers,
> Arthur
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2023-07-21 19:36:34