News for hackers. Stuff that matters.
Re:Just how constexpr is C++20’s std:string? by kccqzy on Friday September 08, 2023 @03:43PM (#37438463)
I find that there's no use case for a constexpr std::string. Maybe I'm just not imaginative enough. If I want a string literal constant, I use string_view which can be constexpr. If somehow I need an actual std::string object, I use a regular const not constexpr. What would be a use case that prompts the author to explore using constexpr with std::string?
Re:Just how constexpr is C++20’s std:string? by fooker on Friday September 08, 2023 @03:58PM (#37438642)
Generate a large number of strings and maps programmatically in compile time.

You are pretty much limited to macros and macro-like languages (llvm-tablegen) if you want to do this today.

Re:Just how constexpr is C++20’s std:string? by mostlylurks on Friday September 08, 2023 @04:19PM (#37438883)
You can also do the same with templates quite easily, but the resulting compile times are going to be absolutely atrocious.
Re:Just how constexpr is C++20’s std:string? by fooker on Friday September 08, 2023 @05:26PM (#37439654)
A bunch of constexpr stuff since C++14 onwards have been added just to make meta-programming more usable.

Users, library writers, and compiler writers all benefit from this in some way.

Re:Just how constexpr is C++20’s std:string? by ghotli on Friday September 08, 2023 @09:20PM (#37441247)
Maybe I'm just not imaginative enough but what sort of use-case is this sort of thing for?
Re:Just how constexpr is C++20’s std:string? by fooker on Saturday September 09, 2023 @06:59PM (#37451136)
Parsers, and any text heavy application really.
Re:Just how constexpr is C++20’s std:string? by hudsonwillis on Friday September 08, 2023 @04:01PM (#37438679)
It enables users to process string at compile time. You can implement a constexpr getRFC3339DateString(int year, int month, int day) -> string and then construct a constexpr string list.
Re:Just how constexpr is C++20’s std:string? by kccqzy on Friday September 08, 2023 @04:43PM (#37439159)
But what can you do with that string list afterwards? You can't store it anywhere to be accessed at run time, can you?
Re:Just how constexpr is C++20’s std:string? by Chabsff on Friday September 08, 2023 @05:05PM (#37439417)
The important part is that all the intermediate strings used during the computation are constexpr, to guarantee that the work happens during compilation.

Also, constexpr symbols can be demoted to regular const as needed by the compiler if necessary, such as when getting a pointer to one. constexpr doesn't mean "compile-time only", it means "compile-time compatible"

Re:Just how constexpr is C++20’s std:string? by lldb on Friday September 08, 2023 @05:44PM (#37439774)
Right - you can use the std::string at compile time but since it allocates dynamically you need to copy to a fixed size char[]/std::array to use at runtime.
Re:Just how constexpr is C++20’s std:string? by dtho on Friday September 08, 2023 @03:56PM (#37438609)
The constructor of std::string is constexpr in C++20. A runtime call to 'strlen' (or equivalent) can be optimized out by computing the string's length at compile time and initializing the object accordingly.
Re:Just how constexpr is C++20’s std:string? by rewmie on Saturday September 09, 2023 @03:55AM (#37443187)
> The constructor of std::string is constexpr in C++20.

If I recall correctly, from C++20 onward all member functions of std::string are constexpr.

Re:Just how constexpr is C++20’s std:string? by maccard on Friday September 08, 2023 @04:05PM (#37438733)
> If I want a string literal constant, I use string_view which can be constexp

That assumes your API accepts string views. How do you pass a string_view (safely) to fopen, or CreateFile (on windows)?

Re:Just how constexpr is C++20’s std:string? by eesmith on Friday September 08, 2023 @04:09PM (#37438767)
While (I think) I understand your broader point, when would you pass a string created by a constexp to fopen() or CreateFile?
Re:Just how constexpr is C++20’s std:string? by cshokie on Friday September 08, 2023 @04:58PM (#37439328)
Hard-coding a relative file path seems like an obvious example. For example a config file with settings. The file will always have the same name so heap allocations and mutability are not needed.
Re:Just how constexpr is C++20’s std:string? by eesmith on Saturday September 09, 2023 @12:31AM (#37442308)
My config file paths have either been constant (".dotfile") or required run-time information that could not be constexpr'ed. I don't see how constexpr would be useful.

Then again, I am primarily a Python and C programmer, so there is likely some underlying reasoning I'm missing.

Re:Just how constexpr is C++20’s std:string? by cshokie on Saturday September 09, 2023 @07:23PM (#37451289)
const std::string foo = “.dot file”;

in C++ cannot change after construction, but is not compile time constant. This means that it has to run some code and allocate some memory at runtime.

In contrast constexpr is fully compile time and ends up in the read only portion of the binary. No code code execution or allocations necessary.

Re:Just how constexpr is C++20’s std:string? by maccard on Friday September 08, 2023 @06:16PM (#37440022)
They were examples, they're widely used C apis. Anything that passes through to glibc, windows or posix will have this problem.
Re:Just how constexpr is C++20’s std:string? by eesmith on Saturday September 09, 2023 @12:26AM (#37442284)
I lack the intuition to understand why is it useful to constexpr path names. Could you elaborate?
Re:Just how constexpr is C++20’s std:string? by maccard on Saturday September 09, 2023 @04:00AM (#37443215)
It's not about path names. It's about passing constexpr strings to c functions that expect a null terminated string. You're totally missing the point.

That said, here's an example:

    // imagine this with string_view
    FILE* openFileInPath(const std::string& path) {
        
        if (path.starts_with("some_dir"))
        {
            return fopen(path.c_str());
        }
    return nullptr;
    }
That function works just fine to only open a path that has a prefix (logic bug on relative paths aside for brevity while posting)

I should be able to pass a constexpr string to that function the same way I can pass a runtime created string.

Re:Just how constexpr is C++20’s std:string? by eesmith on Saturday September 09, 2023 @07:54AM (#37444321)
Oh, I don't doubt I'm missing the point. That's why I'm asking. My C++ experience is from the 1990s. Otherwise I do Python and C.

I think of constexpr functions as something which occur at compile time, and I thought this linked-to piece was about what can take place inside those functions.

As I understand it, you want to create a constexpr string so it can be passed to a char*. The issue is this requires heap allocation (for large enough strings, based on the compiler implementation).

The C programmer in me wonders why you don't "char[]" allocate the static memory buffer, then pass around a string view, so the constexpr doesn't need heap at all.

Re:Just how constexpr is C++20’s std:string? by maccard on Saturday September 09, 2023 @09:00AM (#37444847)
> As I understand it, you want to create a constexpr string so it can be passed to a char*. The issue is this requires heap allocation (for large enough strings, based on the compiler implementation).

There's a few reasons. Avoiding the heap allocation is one, yep. There just shouldn't be a difference between a compile time string and a runtime string. As a programmer I don't want to have to deal with "which flavor of string am I dealing with".

The issue with passing to a c API (I used fopen, but think of any c library - zlib/gzip, openssl, sqlite) is that the string needs to be null terminated, and string view doesn't guarantee null termination.

    int foo(std::string_view view) {
        return strlen(view.data());
    }

    std::string str("hello world");
    foo(str):
    std::string_view view = str;
    foo(view);
    view.remove_suffix(6); // now view is just "hello" with no null termination
    foo(view); // this is wrong.
The problem isn't _specifically_ constexpr std::string in this case, it's that the tools that you use to generalise working with runtime strings, char buffers, and views aren't fit for purpose.
Re:Just how constexpr is C++20’s std:string? by eesmith on Saturday September 09, 2023 @11:26AM (#37446469)
Thank you for your detailed answer.

In the 1990s there was only one string type - NUL-terminated characters. ;)

I keep reading about all the neat algorithms (and multi-threading) support in modern C++, but the complexity of the decades of history and the difference in mindset between {C, Python} and C++ have made me shy away.

I think I'll keep mum from a distance in future discussions until I decided to (re) take up the language seriously.

Re:Just how constexpr is C++20’s std:string? by maccard on Saturday September 09, 2023 @02:26PM (#37448602)
> In the 1990s there was only one string type - NUL-terminated characters.

Indeed. If I could wave a magic wand, I would add a fat pointer to the language that we use to represent strings and arrays, and that we can automatically convert to/from const char* at compile time. This would replace string_view and span. All of the functionality of std::string would be available to it, and a call to strlen, or strcpy on it would work via the length, rather than the null terminator.

But alas, no magic wand.

Re:Just how constexpr is C++20’s std:string? by criddell on Friday September 08, 2023 @05:08PM (#37439458)
Old Windows APIs are a bit of a mess when it comes to const. So many that use LPWSTR strings rather than an LPCWSTR.
Re:Just how constexpr is C++20’s std:string? by o11c on Friday September 08, 2023 @04:52PM (#37439258)
If it was real constexpr it would be useful, e.g. concatenation is commonly desired and requires awkward workarounds currently.
Re:Just how constexpr is C++20’s std:string? by hot_gril on Friday September 08, 2023 @04:54PM (#37439278)
I use constexpr char[] for string literal constants just because it's a little more compatible. Some things can't take string_view.
Re:Just how constexpr is C++20’s std:string? by criddell on Friday September 08, 2023 @05:05PM (#37439413)
Why not use a std::array? Otherwise won't you a second variable for the string length?
Re:Just how constexpr is C++20’s std:string? by hot_gril on Friday September 08, 2023 @05:23PM (#37439610)
`constexpr char kFoo[] = "bar"`, then kFoo can be used like an std::string and passed into things that take const std::string& or string_view. The length is part of that. Or is that actually doing a copy?
Re:Just how constexpr is C++20’s std:string? by vitus on Friday September 08, 2023 @05:44PM (#37439776)
For both const std::string& and std::string_view, you're (potentially) incurring a runtime invocation of strlen.

For const std::string&, you're further incurring a copy in order to create a temporary std::string.

Re:Just how constexpr is C++20’s std:string? by hot_gril on Saturday September 09, 2023 @02:11AM (#37442724)
Whoops. As you can maybe tell, the stuff I use C++ for isn't so much about performance.
Re:Just how constexpr is C++20’s std:string? by criddell on Friday September 08, 2023 @05:46PM (#37439799)
I think you still need the length though unless you can guarantee the string will never have any nulls in it. In Windows, there are API calls that take strings with embedded nulls (and that are typically terminated with a two nulls in a row).

So you might need to deal with a string that looks like "foo\0bar\0\0".

Re:Just how constexpr is C++20’s std:string? by mike_hock on Friday September 08, 2023 @05:14PM (#37439513)
Would definitely be more useful if you could actually materialize the eventual result into something that's visible at runtime.

If there was reflection, it would be useful to talk about class names, function names, etc, at compile time.

Re:Just how constexpr is C++20’s std:string? by scatters on Friday September 08, 2023 @09:03PM (#37441173)
You can use `std::array<char>` (which, as it happens, is a literal type) as an intermediary when performing materialization. A nice toy example is to build a comma-separated string listing enumerators:

    template<class E> requires std::is_enum_v<E> constexpr std::string_view joinedEnum() {
        constexpr auto generate = [] -> std::string {
            return []<template<class...> class L, class... D>(L<D...>) {
                std::string str;
                (((str += (str.empty() ? "" : ", ")) += D::name), ...);
                return str;
            }(boost::describe::describe_enumerators<E>());
        };
        static constexpr auto arr = [&] {
            constexpr std::size_t N = generate().size();
            std::array<char, N> arr;
            std::char_traits<char>::copy(arr.data(), generate().data(), N);
            return arr;
        }();
        return std::string_view(arr);
    }
Note that you have to generate the constexpr std::string twice; once for its size, once for its contents. But you assume that the compiler can memoize the result.
Re:Just how constexpr is C++20’s std:string? by rewmie on Saturday September 09, 2023 @03:53AM (#37443182)
> I find that there's no use case for a constexpr std::string. Maybe I'm just not imaginative enough.

Putting together strings through string interpolation involving somewhat expensive operations is a common usecase. Given the choice, it's preferable to not have to compute them each and every single time a function is invoked.