1

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.

farbiondriven
  • 2,450
  • 2
  • 15
  • 31
  • 3
    Does this answer your question? [Why not always assign return values to const reference?](https://stackoverflow.com/questions/37649236/why-not-always-assign-return-values-to-const-reference) – GoodDeeds Jan 31 '20 at 14:06
  • The question is the same but I'm still not sure about the answer. – farbiondriven Jan 31 '20 at 15:11

2 Answers2

2

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.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
  • @RinatVeliakhmedov In which standard of C++? Haven't you noticed that I was talking about **reference variables**? – Ardent Coder Jan 31 '20 at 14:37
  • No copy is avoided by using reference here. In one case a variable is copy initialised, and in another case a temporary object is copy initialised. – eerorika Jan 31 '20 at 15:06
  • 1
    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. – farbiondriven Jan 31 '20 at 15:08
  • @farbiondriven You are good to go. Don't worry about the scope as I've mentioned in my answer. Do take care that you don't use a reference variable for a dynamically initialized object which may end you up with dangling references but you can make use of smart pointers. – Ardent Coder Jan 31 '20 at 15:16
1
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.

eerorika
  • 232,697
  • 12
  • 197
  • 326