C++ Logo

std-proposals

Advanced search

Re: [std-proposals] consteval .c_str() for string_view

From: JJ Marr <jjmarr_at_[hidden]>
Date: Thu, 3 Jul 2025 21:35:19 -0400
I wasn't aware zstring_view was proposed for standardization. That was the
"option 2" I listed originally.

I believe a consteval `.c_str()` would still have value if that proposal
was adopted, since it means it would still be idiomatic to declare all of
my string literals as `static constexpr std::string_view`, instead of
having to make a decision on C string compatibility every time I bind a
string literal to a variable. In practice, I assume many will declare as
`zstring_view` pre-emptively and pay for a null terminator they don't end
up using.

In contrast, a `consteval .z_str()` function on `std::string_view` or even
an implicit consteval conversion to `zstring_view` would only add the null
terminator to the compile-time string if it's actually needed by a
C-compatible API.

On Thu, Jul 3, 2025 at 8:36 PM Andre Kostur <andre_at_[hidden]> wrote:

> Perhaps you may be interested in
> https://isocpp.org/files/papers/P3655R2.html
>
> On Thu, Jul 3, 2025 at 5:31 PM JJ Marr via Std-Proposals
> <std-proposals_at_[hidden]> wrote:
> >
> > I want to convert over a large codebase away from C-style strings. One
> of the sticking points is compile-time string constants.
> >
> > Modern C++ practice is to use `constexpr std::string_view`. However, I
> cannot easily use that string_view in an interface that accepts
> null-terminated C-style strings. This makes it difficult to do an
> incremental migration.
> >
> > I currently have two options:
> >
> > 1. I can manually add a null-terminator if I want to pass a string_view
> into a function expecting C-style strings. This is confusing and violates
> the intended usage of string_view.
> >
> > 2. I can create my own wrapper of std::string_view that guarantees
> null-termination. However, this isn't idiomatic and project-specific.
> >
> > Instead, I propose to add a `consteval c_str()` function that constructs
> a C-string from a string_view at compile-time. This wouldn't be a good idea
> at runtime (so it can't be `constexpr`) because it would trigger a memory
> allocation on an object that's supposed to be a non-owning reference.
> However, I don't see any issues with this at compile-time, since the
> compiler can figure out what the string_view should look like.
> >
> > What does std-proposals think? Should I write an actual draft?
> > --
> > Std-Proposals mailing list
> > Std-Proposals_at_[hidden]
> > https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2025-07-04 01:35:33