C++ Logo

STD-PROPOSALS

Advanced search

Subject: Re: [std-proposals] Avoid copies when using string_view with APIs expecting null terminated strings
From: Jason McKesson (jmckesson_at_[hidden])
Date: 2020-12-22 23:22:07


On Tue, Dec 22, 2020 at 8:13 PM Thiago Macieira via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> On Tuesday, 22 December 2020 21:33:35 -03 Tom Mason via Std-Proposals wrote:
> > The problem is that there is no way to know if a given string_view is null
> > terminated. My proposal is to add a method bool null_terminated() to
> > string_view. When a string_view is constructed, the caller can tell the
> > implementation that the pointer it is providing is null terminated. The
> > conversion from std::string to std::string_view would set this flag.
>
> This is an ABI-changing proposal. Please provide strong enough motivation to
> warrant it.
>
> Given the cost, it might be worth to have a separate class to indicate zero-
> terminated string views.

It should also be noted that if you have an API that needs a
NUL-terminated string view... then it *needs* a NUL-terminated string
view. That strongly suggests a different type, as that's how we
typically spell such needs in APIs. That way, users using your API can
see what it needs and can provide what you need. They can even
propagate that need up the call graph.

In any case, the thing about such a view is that it should just be a
`char const *` wrapped in an object. It shouldn't have a size member,
and it shouldn't be convertible to/from `string_view`. Also, its range
begin/end functions should be an iterator/sentinel pair, not a pair of
iterators. The sentinel would do the NUL check. I wrote a skeletal
version of such a class and found that compilers were pretty good
about optimizing uses of it down to the equivalent of common C-string
loops.


STD-PROPOSALS list run by std-proposals-owner@lists.isocpp.org

Standard Proposals Archives on Google Groups