简体   繁体   中英

C++ Get result of function returning by value in const reference

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.

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.

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.

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