I have made the following example to test my understanding of references:
#include <iostream>
int test(){
int a = 1;
int &b = a;
return b;
}
int main(int argc, const char * argv[]) {
std::cout << test() << std::endl;
}
What I intended to do is to write an example where the referenced variable is destroyed. I originally wrote this thinking that, since the lifetime of a
in test
ends when returning b
in test
, outputting the return-value of test
produces gibberish. However, to my big surprise, it actually does output 1!
How is this possible? What am I missing here - can a
somehow continue living in b
?
The function does not return a reference to any object. It returns a temporary object of the type int that was copy-initialized by the value referenced by b.
int test(){
int a = 1;
int &b = a;
return b;
}
In fact the function is equivalent to the following function without using intermediate variables
int test(){
return 1;
}
To return a reference means that the function return type should be a referenced type. Something like
int & test()
{
int a = 1;
return a;
}
In this case the compiler will issue a message that the function returns a reference to a local variable.