When would I pass const& std::string instead of std::string_view?

自闭症网瘾萝莉.ら 提交于 2019-12-03 09:57:09

When would I choose std::string by const& instead of string_view for function arguments?

Do you need a null-terminated string? If so, then you should use std::string const& which gives you that guarantee. string_view does not - it's simply a range of const char.

If you do not need a null-terminated string, and you do not need to take ownership of the data, then you should use string_view. If you do need to take ownership of the data, then it may be the case that string by value is better than string_view.

One possible reason to accept const std::string& instead of string_view is when you want to store reference to string object which can change later.

If you accept and store a string_view, it might become invalid when string internal buffer reallocates.

If you accept and store reference to string itself, you won't have that problem, as long as that object is alive (you probably want to delete r-value reference overload, to avoid obvious problem with temporaries).

Andrei Alexandrescu once said, "No Work is better than some work". So you should use const std::string& in such contexts. Because std::string_view still involves some work (copying a pair of pointer and length).

Of course, const references may still have the cost of copying a pointer; which is almost the equivalent of what std::string_view will do. But there's one additional work with std::string_view, it also copies the length.

This is in theory, but in practice, a benchmark will be preferred to infer performance


It is not really what you were asking, but sometimes you want to take std::string by value rather than std::string_view for performance reasons. This is the case when you will need to modify the string before inspecting it:

bool matches(std::string s)
{
  make_upper_case(s);
  return lib::test_if_matches(s);
}

You need a mutable string somewhere anyway, so you may declare it as function parameter. If you changed it to to std::string_view, and somebody passes an std::string to function matches() you would be first converting string to string_view and then string_view to string, and therefore allocating twice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!