Search⌘ K

Choosing between string & string_view

Explore the differences between std::string and std::string_view for string member initialization in constructors. Understand allocation costs, copy behaviors, and when each type is more efficient. This lesson helps you decide the best approach for string parameters and member storage in C++17.

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:

C++
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: ...