C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Return type of string_view::remove_suffix

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Sat, 7 Jan 2023 19:31:41 -0500
On Sat, Jan 7, 2023 at 6:13 PM Arthur O'Dwyer via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> On Sat, Jan 7, 2023 at 2:00 PM Giuseppe D'Angelo via Std-Proposals <std-proposals_at_[hidden]> wrote:
>>
>> On 06/01/2023 17:28, Jason McKesson via Std-Proposals wrote:
>> >> so that we can do stuff like:
>> >>
>> >> string str("monkey5");
>> >> Func( string_view(str).remove_suffix(1u).remove_prefix(2u) );
>> > You could just do this:
>> >
>> > Func(string_view(str.begin()+1, str.end() - 2));
>> >
>> > This requires C++20 for the contiguous iterator support, but it does
>> > work. Note that the remove_* functions exhibit UB if you try to remove
>> > more characters than exist. So the fact that this too will exhibit UB
>> > in those situations is fine.
>>
>> It's completely anti-ergonomic to have to do math like that.
>>
>> Compare with something like Qt, where string classes have functions that
>> mutate in place and functions that return the mutated version:
>> view.chop(N); // mutates in-place, returns void
>> view.chopped(N); // does not mutate, returns a new view
>
>
> I agree with all three guidelines stated so far:
> (1) Math is un-ergonomic.
> (2) Active-verb and past-tense/adjectival-form (sort/sorted, chop/chopped, strip/stripped, trim/trimmed) are the Right Solution.
> (3) Having a method that both mutates and returns reference-to-*this is just asking for misuse, and should be avoided at all costs.
>
> But this particular operation has two unusual problems: we have to think about consistency with the methods that already exist (problem for (2)), and the operation itself is not simple (problem for (1)).
> After all, `string_view` already has a substring method — it's called `substr`!
> Func(str.substr(1, str.size() - 3));
> This is shorter than Jason's
> Func(std::string_view(str.begin()+1, str.end()-2)); // ...or...
> Func(std::string_view(str.data()+1, str.size()-3));

The problem there is that he didn't start with a `string_view`; he
started with a `std::string`. And there is no `substr` equivalent on
`std::string` that yields a view.

Received on 2023-01-08 00:31:49