C++ Logo

std-proposals

Advanced search

[std-proposals] Appending a string to itself

From: Jerry Coffin <jerry.coffin_at_[hidden]>
Date: Fri, 21 Jul 2023 09:58:38 -0700
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);
```

According to recent drafts/standards, this is equivalent to:

```cpp
s.append(s.data(), s.size());
```

We can typically expect that `append` will need to resize the string's
buffer though. And when it does so, it invalidates the pointer it was
passed.

The simplest correction is probably to specify that:

```cpp
s1.append(s2);
```

...is equivalent to:

```cpp
s1.resize(size() + s2.size() + 1);
return append(s2.data(), s2.size());
```

Received on 2023-07-21 16:59:13