Dieses Beispiel zeigt/bestätigt wieso wir in dem Fall der Funktion foo3 tatsächlich eine Referenz (in diesem Fall eine const Referenz) zurück geben können. Wir sehen, dass die Adressen die gleichen Werte haben, d.h. die Variablen verweisen auf die gleiche Stelle im Memory.
#include
unsigned int foo1(int &i) { return ++i; }
// error
unsigned int &foo2(int i) { return ++i; }
const int &foo3(int &i)
{
std::cout << "Address of Variable with name 'i': " << &i << std::endl; // print address of i: it is same as address of a, as it is
// just a reference (i.e. "other name") to a
return ++i;
}
int main()
{
int a = 5;
std::cout << "Address of Variable with name 'a': " << &a << std::endl; // print address of a
int &b = a; // reference to a, as we have seen before
std::cout << "Address of Variable with name 'b': " << &b << std::endl; // print address of b, is the same as address of a
int res1 = foo1(a); // after this line: a is 6 and res1 is 6
std::cout << a << ", " << res1 << std::endl;
std::cout << "&res1: " << &res1 << std::endl; // print address of res1, is new variable so it has new location
const int &res3 = foo3(a); // how you could use foo3, now we have a const ref...
std::cout << a << ", " << res3 << std::endl; // ... that we can read from (e.g. to print) but we can't change it
std::cout << "Address of Variable with name 'a': " << &a << std::endl; // we print the addresses of a...
std::cout << "Address of Variable with name 'res3': " << &res3 << std::endl; // ... and res3 and see they are indeed the same
return 0;
}