I'm developing a dynamic library, and for ABI-stability, I'm using a std::string_view
-like class for passing read-only, non-owning strings.
A third-party library I'm using under the hood uses const std::string&
for such purposes, and therefore I have to do something like std::string { view.data(), view.size() }
whenever I call into that library, which incurs an unnecessary allocation.
Is there a way to handle this conversion without relying on compiler-specific std::string
implementation details?
I think I can potentially use string interning or some form of caching if I know the number of strings I'll deal with is relatively small. However, this is not the case for my library because the user may pass arbitrary strings.
Using a custom allocator would make the string a different type, so that is not viable either.
The "efficient converting" is not defined, so I guess the OP assumes avoiding copying a buffer pointed by a string view. This is impossible in all cases.
std::string_view::data()
returns a pointer to a buffer that is not necessarily null-terminated.std::string::data()
returns a null-terminated array.std::string
must append the null to a string view buffer, it can be made only after copying a buffer pointed by a string view.