Why does this code work? It prints out 60
every single time. First of all, const thingy&
indicates that the function returns a reference to an already existing variable, not a nameless construction. Secondly, shouldn't that temporary die when the function returns, thus creating a null reference? I am using whatever the latest GCC version is on OSX... Can somebody please explain to me why this works?
#include <iostream>
using namespace std;
struct thingy {
double things;
double moreThings;
double evenMoreThings;
};
const thingy& getThingy() {
return {60, 60, 60};
}
int main() {
cout << getThingy().evenMoreThings << endl;
}
And if that works, then why doesn't this?
const thingy& getThingy() {
thingy t{60, 60, 60};
return t;
}