首页 > 解决方案 > 在构造函数中初始化字符串成员的首选方法是什么?

问题描述

下面是一个有一个字符串成员的类。我们想在构造函数中初始化它:

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) };

标签: c++c++17

解决方案



推荐阅读