问题
By getting string_view
in C++17 we got cheap method of passing both std::string
and char*
to functions that do not take ownership of the string and avoid making temporary copies. By using std::string
passed by value and std::move
we get explicit and fast passing of string ownership for both r-value and l-value references.
My question is: is there any benefit in using const std::string&
as any function parameter in new C++ standard?
回答1:
Yes.
The problem with std::string_view
is that it doesn't remember if it points to a null-terminated string or not.
If you're writing a wrapper for a C api that uses null-terminated strings, you would have to constantly copy your std::string_view
s into std::string
s to make sure you have null-terminators.
来源:https://stackoverflow.com/questions/57951871/is-there-sense-in-using-const-stdstring-arguments-in-c17