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?
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With