c++ - 在构造函数中初始化字符串成员的首选方法是什么?
问题描述
下面是一个有一个字符串成员的类。我们想在构造函数中初始化它:
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) };
解决方案
推荐阅读
- python - 如何使用 object.id 创建另一个对象,即当前对象的创建者?
- mysql - maxscale 找不到 gtid_binlog_pos
- javascript - React Native 错误:列表中的每个孩子都应该有一个唯一的“关键”道具
- docker - docker ps 命令不返回任何内容
- node.js - 无法从对象数组中删除重复项
- r - 使用 scale_x_discrete 后如何更改 ggh4x 包中的标签角度
- path - Jupyter Lab 在错误的路径中打开,与 Jupyter Notebook 不同,两者在“jupyter_notebook_config.py”中具有相同的映射。
- linux - 在共享 docker 卷中,某些文件有时会丢失
- java - 有没有办法在不返回任何内容的情况下运行 java 流?
- ssl - 网桥上的 Mosquitto 代理 ACL 列表