以下是一个具有一个字符串成员的类。我们希望在构造函数中初始化它:
构造函数接受const std::string&参数。
我们可以使用string_view替换常量引用:
class MyStr {
std::string m_str;
public:
MyStr(const std::string& rstr) : m_str(rstr) {}
};
构造函数接受const std::string&参数。
我们可以使用string_view替换常量引用:
MyStr(std::string_view strv) : m_str(strv) {}
或者将字符串按值传递并从中移动:
MyStr(std::string str) : m_str(std::move(str)) {}
哪个方案更好?
3种情况:
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) };