Skip to content

The constructor std::string(std::string_view) from libstdc++ can't be evaluated at compile-time #161071

@HolyBlackCat

Description

@HolyBlackCat

When using libstdc++, the following refuses to evaluate at compile-time: (in Clang, but not in GCC)

#include <string>
#include <string_view>
constexpr std::size_t i = std::string(std::string_view("42")).size();

With the following error:

<source>:4:23: error: constexpr variable 'i' must be initialized by a constant expression
    4 | constexpr std::size_t i = std::string(std::string_view("42")).size();
      |                       ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/16.0.0/../../../../include/c++/16.0.0/bits/basic_string.h:692:2: note: undefined function '_M_construct<const char *>' cannot be used in a constant expression
  692 |         _M_construct(__s, __s + __n, std::forward_iterator_tag());
      |         ^
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/16.0.0/../../../../include/c++/16.0.0/bits/basic_string.h:193:9: note: in call to 'basic_string(&"42"[0], 2, std::allocator<char>())'
  193 |       : basic_string(__svw._M_sv.data(), __svw._M_sv.size(), __a) { }
      |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/16.0.0/../../../../include/c++/16.0.0/bits/basic_string.h:888:4: note: in call to 'basic_string({{2, &"42"[0]}}, std::allocator<char>())'
  888 |         : basic_string(__sv_wrapper(_S_to_string_view(__t)), __a) { }
      |           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:4:27: note: in call to 'basic_string<std::basic_string_view<char>, void>(std::string_view("42"), std::allocator<char>())'
    4 | constexpr std::size_t i = std::string(std::string_view("42")).size();
      |                           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/16.0.0/../../../../include/c++/16.0.0/bits/basic_string.h:343:9: note: declared here
  343 |         _M_construct(_FwdIterator __beg, _FwdIterator __end,
      |         ^
1 error generated.

GCC has no problem with this, so I'm not sure where it needs to be fixed, in Clang or in libstdc++.

Tested on Clang 21 with libstdc++ 15: https://gcc.godbolt.org/z/8Y3s87Y1G

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:frontendLanguage frontend issues, e.g. anything involving "Sema"constexprAnything related to constant evaluationduplicateResolved as duplicatelibstdc++GNU libstdc++ C++ standard library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions