Reputation: 5805
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();
Upvotes: 24
Views: 16249
Reputation: 137850
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-onlyauto &
should mean read-writeauto &&
should mean catch all, perhaps adopting a return by value objectUpvotes: 9
Reputation: 126492
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();
Upvotes: 17
Reputation: 171167
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."
Upvotes: 9