C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Forbid optimisations on std::basic_string implementations.

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Mon, 18 Aug 2025 17:08:17 +0300
On 18 Aug 2025 15:52, Simon Schröder via Std-Proposals wrote:
> On 18. Aug 2025, at 13:56, Bo Persson via Std-Proposals <std-proposals_at_[hidden]> wrote:
>>
>> On 2025-08-18 at 13:18, Andrey Semashev via Std-Proposals wrote:
>>> On 18 Aug 2025 13:33, Ben Crowhurst via Std-Proposals wrote:
>>>>
>>>> There is a history of STL implementations introducing string
>>>> optimisations, for example, copy-on-write in GCC (<=4), adoption of
>>>> small string optimisation (SSO) - with varying details across GCC,
>>>> Clang, and MSVC.
>>>>
>>>> Focusing on SSO, using std::string, along with std::string_view and move
>>>> semantics, introduces a frustrating folly.
>>> Why? What is the problem with SSO?
>>
>> If you get a string_view to a string, and then move the string, the string_view may, or may not, move along - all because of SSO.
>
> If you have a string_view or a span to a moved from object there is no reason to believe that the view/span is still valid. It is at least implementation defined behavior if not undefined behavior. If the view still works after a move you just got lucky. It is quite similar for iterators to be invalid for some containers after certain operations on the container.
>
> This is certainly not a reason to disallow SSO. If you need a string+string_view with a specific behavior you should implement your own. (Hopefully compatible/convertible to a std::string.)

Absolutely.

I will add that the C++ standard specifies that std::basic_string move
constructor leaves the move source in a valid but unspecified state
(meaning that it is unspecified whether pointers and references into the
moved-from string remain valid) and the move assignment explicitly
permits pointers and references into the move source to be invalidated.
So, no valid code today can rely on the behavior Bo described.

Received on 2025-08-18 14:08:21