As a simple test case for much larger code, I want to pass std::string_view as a param to a function taking an arg of const std::string&. This isn't accepted without first creating a temp std::string. Is there any way of passing a std::string_view to a const std::string& without doing a copy? Effectively I want to do:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <string>
#include <string_view>
void func1(const std::string& str) {
// Process str
}
int main() {
const std::string_view sv {"qwerty"};
func1(std::string(sv)); // OK but expensive as does a copy
//func1(sv); // Wanted but doesn't compile
}
Yes, the arg of func1() could be changed to std::string_view but in the actual code func1() calls other functions which use const std::string& which in turn themselves call other functions etc.... I'd prefer not to start down that rabbit hole if there's a simple alternative. This usage for passing a std::string_view to a const std::string& by creating a temp std::string currently occurs many times in the actual code. Whether a function uses std::string_view or const std::string& seems to depend upon how old is the code and the programmer who wrote the functions!
Is there any way of passing a std::string_view to a const std::string& without doing a copy?
How could it be? std::string owns its data. std::string_view doesn't. That means that even if the std::string_view was an rvalue the std::string wouldn't be able to "steal" the data from it.