首页 > 解决方案 > 由于方法重载,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:问题的printstd::string部分用作示例。它们可以是任何东西。

编辑#3:重命名示例代码。这些方法确实修改了 Thing 对象。

标签: c++

解决方案


如果print不更改任何内容并且只打印字符串,则最好采用能够绑定到左值和右值的 as const std::string &const std::string &

int print(const std::string& text) {}

推荐阅读