string_view
vs const string&
When should I use std::string_view
instead of const std::string&
?
std::string_view
and const std::string&
are both used for read-only access to strings, but they have different use cases and benefits.
Use std::string_view
when:
- You need to provide a unified interface for different string types (e.g.,
std::string
, C-style strings, and string literals). - Performance is critical, and you want to avoid unnecessary copying.
- You are working with substrings or portions of strings without copying.
Use const std::string&
when:
- You are certain that your function will only accept
std::string
objects. - The lifetime of the string is tightly controlled, and there is no risk of dangling references.
Here's an example comparing the two:
#include <iostream>
#include <string>
#include <string_view>
void printStringView(std::string_view sv) {
std::cout << sv << '\n';
}
void printConstStringRef(const std::string& str) {
std::cout << str << '\n';
}
int main() {
std::string str{"Hello, world"};
// Works with std::string
printStringView(str);
// Works with C-style string
printStringView("Hello, C-style string");
// Works with std::string
printConstStringRef(str);
// Error: incompatible types
// printConstStringRef("Hello, C-style string");
}
Hello, world
Hello, C-style string
Hello, world
In summary, std::string_view
offers greater flexibility and efficiency when handling various string types and avoiding unnecessary copying.
However, const std::string&
is straightforward and ideal for cases where you are sure only std::string
objects will be used.
String Views
A practical introduction to string views, and why they should be the main way we pass strings to functions