c++ - 由于方法重载,C++ 移动语义和代码重复
问题描述
在开始之前,我在另一篇 stackoverflow 帖子中没有找到任何可以完全解释我的问题的内容,因此我决定创建自己的。抱歉,如果它已经在其他地方得到了回答(如果它确实存在,请指出我现有的帖子)。
假设我们在一个类中有以下两种方法:
int do_stuff(Thing& thing){ /* Do stuff... */} // L-value version
int do_stuff(Thing&& thing){ /* Do stuff... */} // R-value version
根据我的阅读,现代 C++ 几乎已经放弃了这种逻辑,建议只传递Thing
按值并让编译器发挥作用。我的问题是,如果我想有两种单独的方法来显式处理 L 值/R 值并避免代码重复,那么以下哪个是最好的(性能方面和最佳实践)?
int do_stuff(Thing& thing){ return do_stuff(std::move(thing)); } // The L-value version uses the R-value one
或者
int do_stuff(Thing&& thing){ return do_stuff(thing); } // The R-value version uses the L-value one since text is an L-value inside the scope of do_stuff(Thing&&)
编辑:这个问题的目的是让我理解这个简单的移动语义案例,而不是创建一个有效的 C++ API。
编辑#2:问题的print
和std::string
部分用作示例。它们可以是任何东西。
编辑#3:重命名示例代码。这些方法确实修改了 Thing 对象。
解决方案
如果print
不更改任何内容并且只打印字符串,则最好采用能够绑定到左值和右值的 as const std::string &
。const std::string &
int print(const std::string& text) {}
推荐阅读
- react-native - 视频的背景音频 react-native-video
- javascript - 我在尝试导航到未捕获的标签页时遇到此错误(承诺):无效链接:TabsPage
- ruby-on-rails - 如何使用 Highcharts 和 chartkick 设置类别类型?
- .net - 不再获取 Microsoft Docs VB.NET 示例。它们都在 C# 中
- python - 将选项卡 txt 转换为 CSV 批处理
- angular - 角度单选按钮的动态列表
- arrays - 如何在 ruby 中定义哈希对象数组?
- python - 如何使用 python (v3.7) 从 gmail gmail-api 读取消息(HTML 格式)?
- python - 将 JSON API 结果导出到 CSV 文件(垂直与标题)
- excel - 在 Power Query 的每一行中检查特定字符的出现