std::string_view
and const std::string&
are both used for read-only access to strings, but they have different use cases and benefits.
std::string_view
when:std::string
, C-style strings, and string literals).const std::string&
when:std::string
objects.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.
Answers to questions are automatically generated and may not have been reviewed.
A practical introduction to string views, and why they should be the main way we pass strings to functions