使用const std :: string&是否有意义? C ++ 17中的参数? [英] Is there sense in using const std::string& arguments in C++17?
问题描述
通过在C ++ 17中获取 string_view
,我们得到了一种便宜的方法,它同时传递 std :: string
和 char *
表示不获取字符串所有权并避免创建临时副本的函数。通过使用按值传递的 std :: string
和 std :: move
,我们可以显式且快速地传递字符串所有权
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.
我的问题是:使用 const std :: string& $有什么好处? c $ c>作为新的C ++标准中的任何函数参数?
My question is: is there any benefit in using const std::string&
as any function parameter in new C++ standard?
推荐答案
是。
std :: string_view
的问题在于,它不记得是否指向以空值结尾的字符串。
The problem with std::string_view
is that it doesn't remember if it points to a null-terminated string or not.
如果要为使用空值终止的字符串的C api编写包装,则必须不断复制 std :: string_view
s放入 std :: string
s中,以确保您具有空终止符。
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.
这篇关于使用const std :: string&是否有意义? C ++ 17中的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!