C++ › Strings & string_view
What is the difference between passing const std::string& and std::string_view?
AdvancedAnswer
const std::string& avoids a copy but forces the caller to have (or construct) a std::string—a string literal creates a temporary std::string. std::string_view accepts any character source (literal, std::string, substring) without constructing a string, and is cheap to copy. Prefer string_view for read-only parameters, unless you need a null-terminated string or to store it.
void a(const std::string& s); // literal -> temp std::string
void b(std::string_view s); // literal -> no allocationReal-world example Switching read-only APIs to string_view removes hidden std::string temporaries from literal arguments.