如何在const和&中使用auto在C ++中? [英] How to use auto with const and & in C++?
本文介绍了如何在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();
这篇关于如何在const和&中使用auto在C ++中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文