是时候放弃在函数参数中使用 const std::string& 了吗?
大家好!我是 C++ 新手,经常在旧教材和文章中看到建议将字符串作为 const std::string& 传递给函数。但最近我偶然看到一个讨论,说在 C++11 及更新版本中,这已经不是最佳实践了。据说由于 move 语义,按值传递字符串比按常量引用传递更高效。
我完全糊涂了。以下是我的代码示例:
```cpp
void processData(const std::string& name) {
// ... 对 name 进行一些操作,但不复制
std::cout << name << std::endl;
}
void storeData(const std::string& name) {
// 这里我想将 name 保存到类成员中
m_name = name; // 这是复制吗?
}
```
第一种情况只是读取字符串。第二种情况是保存到对象字段中。const std::string& 真的过时了吗?什么时候应该使用它,什么时候应该按值传递字符串(std::string)?或者也许应该使用 std::string_view?恳请用通俗易懂的方式解释,并附上示例,说明哪种方案更优。