Below is a class with one string member. We’d like to initialise it in the constructor:
class MyStr { std::string m_str; public: MyStr(const std::string& rstr) : m_str(rstr) {} }; The constructor takes const std::string&.
We could replace a constant reference with string_view:
MyStr(std::string_view strv) : m_str(strv) {} Or pass a string by value and move from it:
MyStr(std::string str) : m_str(std::move(str)) {} Which of the alternatives is preferred?
3 cases:
MyStr mystro1{"Case 1: From a string literal"}; std::string str2 { "Case 2: From l-value"}; MyStr mystro2 { str2 }; std::string str3 { "Case 3: From r-value reference"}; MyStr mystro3 { std::move(str3) };