On 03/09/24 2:09 AM, Marcel Mueller wrote:
std::string might require allocation if it has no small string
optimization build in.
True. SSO is not required, but virtually all competent implementations
do it.
Furthermore it cannot be initialized from old C
style APIs that require char* buffer and size_t buffer_size.
That is not true.
A non-const version of `std::string::data()` was added in C++17
specifically to support this usage model. (But even before that you
could gain non-const access to its internal buffer through `&str[0]`).
You can pre-`resize()` an `std::string`, pass its `data()` (and `size()`
) to a C function, determine the resultant length based on zero
terminator's location, and then `resize()` it to the new length.
Done.
The idea is to return std::array<char,10> or something like that. This
causes no allocation and the compiler should be able to optimize the
return value to emplace the result into the callers storage.
Is it reasonable to return small strings a std::array to avoid copying?
If you are sure that they will always fit into the pre-determined (at
the compile time) size, then perhaps it might be reasonable. Basically,
the main benefit I can see here is that it allows one to extend SSO-like behavior beyond the boundary used by the existing `std::string`
implementation. I.e to avoid involving dynamic memory for a greater
range of string lengths.
--
Best regards,
Andrey
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)