简体   繁体   中英

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

I have a method that returns const A &.

If I want to use auto, what is the right way to do it. 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() .

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& .

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." Just auto & says simply "I want a reference to what is returned."

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 & should mean read-only
  • auto & should mean read-write
  • auto && should mean catch all, perhaps adopting a return by value object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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