Assume I have the following function:
std::string greeting(const std::string_view name){
return std::string(name) + " we wish you a very nice day and week and month and year";
}
It works fine, but I want to avoid more than 1 memory allocation, assuming name is too long to fit into SSO buffer. So I came up with this:
std::string greeting_efficient(const std::string_view name){
constexpr std::string_view suffix = " we wish you a very nice day and week and month and year";
std::string result;
result.reserve(name.size()+suffix.size());
result+=name;
result+=suffix;
return result;
}
AFAIK it works but it is quite ugly, is there a easier way to do this?
I am fine with using C++20/23 if solution needs it.