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

问题描述:

我有一个返回const A&的方法。

I have a method that returns const A &.

如果我想使用auto,什么是正确的方法。

If I want to use auto, what is the right way to do it. Is this OK?

const auto &items = someObject.someMethod();

我看到有人这样做:

auto &items = someObject.someMethod();

我不确定要使用哪个,真正的区别是什么...

I am not sure which one to use, and what are the differences really...

编辑:

在这种情况下,这两个是否相等?

In this case, are these two equivalent?

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


即使两种形式在在这种情况下,我还是会选择第一种形式,因为它可以更好地传达以下事实:您的代码段不需要修改 someMethod()$返回的对象的状态。 c $ c>。

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().

所以我的建议是这样做:

So my advice is to go for this:

const auto &items = someObject.someMethod();