Reputation: 2468
I have the following example:
struct A
{
...
};
a function returning A by value
A getFoo()
{
A a;
...
return a;
}
The caller only needs to read that output data.
const A& a = getFoo();
Is it a bad approach ? Should it be ?
const A a = getFoo();
My only concern is about scope. I don't care about modifications, I only need to read. I only care about avoid creating unnecessary copies and not ending with dangling references.
Upvotes: 1
Views: 241
Reputation: 238311
const A& a = getFoo();
Is it a bad approach ? Should it be ?
const A a = getFoo();
Former introduces unnecessary indirection and gives no benefit as far as I can tell. Latter is simpler to understand (no need to know about lifetime extension of temporaries bound by references) which makes it better.
Upvotes: 1
Reputation: 3995
That's not a bad approach at least in the code snippet you have shown. It is instead good in the sense that you avoided a copy of the return value thereby increasing the performance of your code.
However, you are now restricted to not modify that value. If you are not okay with it then the second approach is better. In fact, choosing one over the other depends on a particular scenario. It's hard to say in general.
Note that you cannot do it with a non-const reference because it is not allowed to bind the temporary to a non-const reference.
And don't worry about the scope of the value returned by the function. It has now got the scope of your reference variable.
Upvotes: 2