Reputation: 23
I am quite a newbie to the C++ programming, but this question keeps on spinning in my head. I understand that returning reference to a local variable in a function is illegal, i.e. compiling this code snippet:
inline int& funref() {
int a = 8;
return a; // not OK!
}
results in a warning from the compiler and then a runtime error. But then, why does this piece of code get compiled without any warnings and run without error?
inline int& funref() {
int a = 8;
int& refa = a;
return refa; // OK!
}
int main() {
int& refa = funref();
cout << refa;
}
My compiler is g++ on Linux Fedora platform.
Upvotes: 2
Views: 122
Reputation: 1103
The reason why you can't return a reference to a local variable is because the local variable will get wiped when your function returns. Simply put, the compiler prevents you from referencing garbage data.
However, the compiler isn't bulletproof (as shown in your example #2).
It does work for retrieving a singleton instance, though.
inline int& funref()
{
static int* p_a = nullptr;
if (nullptr == p_a)
p_a = new int(8);
return *p_a;
}
this case is valid because the memory pointed by p_a remains valid after the function returns.
Upvotes: -3
Reputation: 67723
It's still wrong, it just happens to be working by (un)happy coincidence.
This code has undefined behaviour with all the usual caveats (it might always work, it might always work until it's too late to fix, it might set fire to your house and run away with your betrothed).
The compiler isn't required to issue a diagnostic (warning or error message) for every possible mistake, just because it isn't always possible to do so. Here, at least your current version of g++ hasn't warned. A different compiler, or a different version of g++, or even the same version with different flags, might warn you.
Upvotes: 5