C++ Logo

std-proposals

Advanced search

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

From: Desmond Gold <desmondbongcawel922_at_[hidden]>
Date: Fri, 4 Jul 2025 09:29:42 +0800
What about `std::define_static_string` in wg21.link/p3491? It's already in
C++26

On Fri, Jul 4, 2025 at 8:31 AM 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:30:02