Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return by value assigned to const reference

Tags:

c++

I was fixing another bug in some code and came across some code that I would have thought was a bug; however, this code compiles under gcc 4.4, 4.5, and 4.6 and appears to function as "expected". Can anyone tell me if this is valid c++?

struct foo {
     int bar;
};

foo myfunction(foo const &orig) {
    foo fooOnStack = orig;
    fooOnStack.bar *= 100;
    return fooOnStack;
}

void myOtherFunction(foo const &orig) {
    foo const &retFoo = myfunction();
    // perhaps do some tests on retFoo.bar ...
}

If this is valid c++, does anyone know the rationale behind this being legal?

like image 731
graphicsMan Avatar asked Sep 07 '11 21:09

graphicsMan


People also ask

Can const function return value?

The reason const has no meaning when you're returning a built-in type by value is that the compiler already prevents it from being an lvalue (because it's always a value, and not a variable). Only when you're returning objects of user-defined types by value does it become an issue.

How do I pass a const reference?

When you pass by const reference, you take the argument in by reference (avoiding making any copies of it), but cannot make any changes to the original object (much as would happen when you would take the parameters in by value).

Can you change the value of const reference?

Const Reference to a pointer is a non-modifiable value that's used same as a const pointer. Here we get a compile-time error as it is a const reference to a pointer thus we are not allowed to reassign it.


1 Answers

Yes, this is legal C++. Forming a reference-to-const to a temporary extends the lifetime of the temporary to the lifetime of the reference.

like image 86
PlasmaHH Avatar answered Sep 24 '22 07:09

PlasmaHH