by eesmith · 3y ago · 0 comments
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.
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.
Then again, I am primarily a Python and C programmer, so there is likely some underlying reasoning I'm missing.
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.