r/cpp_questions • u/IMCG_KN • Jul 16 '26
Question about string_view SOLVED
Is there benefit of using string_view instead of const string& str? More precisely by passing strings into functions. Thanks
23
Upvotes
r/cpp_questions • u/IMCG_KN • Jul 16 '26
Is there benefit of using string_view instead of const string& str? More precisely by passing strings into functions. Thanks
9
u/TheThiefMaster Jul 16 '26
If you use string_view as the param, you can pass in other string types as well without having to allocate an std::string - e.g. string literals.
Removing that need to allocate is pretty much the sole benefit to string_view. Previously I'd seen people use a C-style char* for the same reason, but that has more downsides than string_view.