jeanluc
jeanluc

Reputation: 1708

Advantages of std::string_view when passing to another function taking std::string

I have the following helper function, which takes in a string view and returns a lookup in an unordered_map:

int Scanner::getOpCount(std::string_view op) {
    auto itr = Parser::opTable.find(op);
}

// in another file: 
const static std::unordered_map<std::string, OpEntry> opTable;

This will not compile because find expects a string parameter, so the only solution I've found (correct me if I'm wrong) is to wrap op as string{op}. What worries me, however, is that std::string_view was meant to facilitate easier string passing, but if I have to construct a string from it regardless in the body of the function, then is there any advantage to defining getOpCount with a string_view parameter? Or is this equivalent, if not slower to const std::string&?

Upvotes: 5

Views: 1178

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474476

You need to properly propagate your needs and expectations up your API chain. Your lower-level code needs a std::string; it cannot work with anything else. So that need ought to be propagated up through code that interacts with it, and that with others.

You use string_view when the eventual consumer of that string can work with string_view or its pointer+size components (or the consumer intends to copy the string regardless). If it can't work with string_view, then you can't use it.

Upvotes: 2

Related Questions