...

/

Choosing between string & string_view

Choosing between string & string_view

We should be clear on why we choose a string_view instead of a string. Let's figure it out with the help of an example.

We'll cover the following...

Since string_view is a potential replacement for const string& when passing in functions, we might consider a case of string member initialization​. Is string_view the best candidate here?

For example:

Press + to interact
class UserName {
std::string mName;
public:
UserName(const std::string& str) : mName(str) { }
};

​As you can see a constructor is taking const std::string& str.

You could potentially replace a constant reference with string_view:

UserName(std::string_view sv) : mName(sv) { }

Let’s compare those alternatives implementations in three cases: ...