【发布时间】:2020-09-22 17:54:33
【问题描述】:
假设我有
class Container {
public:
T getValue() const { return t; }
const T& getCRef() const { return t; }
private:
const T t;
};
void f(const T& arg) { ... }
在函数内部临时绑定返回值的首选方法是什么?例如。我应该更喜欢什么,为什么?
void method(const Container& c) {
auto t1 = c.getValue();
auto t2 = c.getCRef();
const auto& t3 = c.getValue();
const auto& t4 = c.getCRef();
// Notes from discussion:
// 1. Neither Container not object T changes during execution
// 2. I don't need to modify T, just passing it through
f(t1);
f(t2);
f(t3);
f(t4);
}
我的理解是:
- t1 将受益于复制省略,并将导致一个复制构造
- t2 也会生成一个副本结构
- t3 仍会导致返回的临时复制构造,然后由 const 引用绑定
- t4 不应该是副本
正确吗?如果是这样,对于这种情况,我是否应该一直更喜欢const auto& 而不是auto?另外,当我可以保证引用与底层对象一样长时,我是否应该更喜欢getCRef() 接口而不是getValue()?
【问题讨论】:
标签: c++