Jean-Marc Lasgouttes schrieb:

Yes, but what if I keep a reference to the temporary variable that gets returned? Does my reference point to neverland?

Yes it does. Or more precisely it points to somewhere on the stack because local variables in functions are allocated on the stack. When the function returns a reference (or a pointer) to such a variable then calling another function most likely overwrites the content of that variable.

e.g. try this one

#include <iostream>

struct T {
   int x;
};

struct U {
   char c1;
   char c2;
   char c3;
   char c4;
};

T &Foo() {
   T t;
   t.x = 1;
   return t;
}

void Bar() {
   U u;
   u.c1 = 0x12;
   u.c2 = 0x34;
   u.c3 = 0x56;
   u.c4 = 0x78;
}

int main() {
   T const& t = Foo();
   std::cout << std::hex << t.x << std::endl;
   Bar();
   std::cout << std::hex << t.x << std::endl;
   return 0;
}

Output is:
1
78563412


bernhard

Reply via email to