简体   繁体   English

如何在C ++中使用const和const?

[英]How to use auto with const and & in C++?

I have a method that returns const A &. 我有一个返回const A&的方法。

If I want to use auto, what is the right way to do it. 如果我想使用auto,那么正确的方法是什么。 Is this OK? 这个可以吗?

const auto &items = someObject.someMethod();

I see some people do this: 我看到有些人这样做:

auto &items = someObject.someMethod();

I am not sure which one to use, and what are the differences really... 我不确定使用哪一个,真的有什么区别......

Edit: 编辑:

In this case, are these two equivalent? 在这种情况下,这两个是等价的吗?

auto items = someObject.someMethod();
auto &items = someObject.someMethod();

Even though the two forms are equivalent in this case , I would choose the first form anyway, since it communicates better the fact that your piece of code does not need to modify the state of the object returned by someMethod() . 即使这两种形式在这种情况下是等价的,我仍然会选择第一种形式,因为它更好地传达了这样一个事实:你的代码片段不需要修改someMethod()返回的对象的状态。

So my advice is to go for this: 所以我的建议就是这样做:

const auto &items = someObject.someMethod();

In your case, there is no difference. 在你的情况下,没有区别。 The type which auto represents will be deduced to const A in both cases, so the type of items will be const A& . 在两种情况下, auto表示的类型将推导为const A ,因此items的类型将为const A&

There is a difference in what the "self-documented semantics" of the code is. 代码的“自我记录的语义”有所不同。 The const auto & clearly states "I want a reference to what is returned, and I will not modify it." const auto &明确指出“我想要引用返回的内容,我不会修改它。” Just auto & says simply "I want a reference to what is returned." 只是auto &简单地说“我想要一个对返回内容的引用”。

More explicitness is usually better, the exception being separation of concerns. 更明确的通常是更好的,例外是关注点的分离。 Implementation details shouldn't be mentioned on the client side of an interface. 不应在接口的客户端提及实现细节。

If the receiver isn't supposed to care how the object is being received, then perfect forwarding is the way to go. 如果接收器不应该关心如何接收对象,那么完美的转发是可行的方法。

auto && items = someObject.someMethod();

Allowing const to be deduced in auto and, for example, binding a temporary value to auto & would be a major code smell for me. 允许在auto中推导const ,例如,将临时值绑定到auto &这对我来说是一个主要的代码味道。

  • auto const & should mean read-only auto const &应该是只读的
  • auto & should mean read-write auto &应该是读写
  • auto && should mean catch all, perhaps adopting a return by value object auto &&应该意味着捕获所有,也许采用按值返回的对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM