C++ Logo

std-proposals

Advanced search

Re: [std-proposals] [Idea] Null-terminated string view (c_str_view / c_wstr_view) – a simpler alternative/complement to zstring_view

From: Jan Schultke <janschultke_at_[hidden]>
Date: Sun, 1 Feb 2026 06:42:33 +0100
>
> > //--------------------------------------------------
> > inline basic_c_str_view(const T *txt, size_t size)
> > {
> > if(txt[size] != (T)'\0') [[unlikely]]
> > throw runtime_error("txt is not null-terminated");
> >
> > m_data = txt;
> > m_size = size;
> > }
>
> This constructor should not exist. The size MUST be determined from the
> actual
> string length and nothing else.
>
> The only value of this constructor would be to throw an exception if the
> actual size differs from the expected one, which I don't think is that
> valuable.
>

Opinions on this are obviously a bit torn, but LEWG essentially decided to
have this already. In Sofia, there was no consensus to ban nested nulls,
and the status quo is to allow them. P3655R3 also has this constructor.

The point of this constructor is to permit zero-overhead construction from
an existing null-terminated C-string, with size information available. This
case is extremely common when initializing from strings returned by C APIs
or from user-defined containers in the style of std::string.

>From your other comments, it sounds like you would want a lack of nested
nulls to be an invariant of std::cstring_view. I strongly disagree with
this direction due to overhead. It's also not like string views can enforce
invariants regarding their content anyway. A user could always construct a
std::cstring_view and then embed a null in the original content. While one
could equally argue that the string view cannot guarantee that its null
terminator remains present, this can at least be asserted on debug builds
whenever the type is used. That is, whenever performing an operation, one
could assert that data[size()] is still null. Rescanning the entire string
is not realistic due to performance cost, so this invariant is not only
unenforceable, it also cannot be sanity-checked. That sounds like adding
more undiagnosable UB to the library; we don't need that.

Received on 2026-02-01 05:42:50