That happens because when pointer or reference invalidates, be it because of dynamic memory deallocation or popping value out of stack, it doesn't just vanish. Instead, memory which contained said variable marked as "free" and can be reused. But it might not be reused immideatly and variable still can be accessed for some time but nobody knows, when that memory will be overwritten.
Not working string probably caused by fact that string is not a simple type and destructor which called at the end of function can make some internal pointers point to 0 which will cause error if you will try to use method accessing those.
There is no reference operator, and there is no notion of addresses here. What's returned are dangling references (references which refer to an invalid object.) We know references are returned, because the functions say they return references.
cire's code isnt showing you adresses. It shows garbage values which just happens to be in place where reference point to. It can be anything from second letter of str argument to half of return address of function and another half of return value of previous function. Actual value will change everytime you do something with your code. I had
cire, the code you gave, it's not cout << &r1;, why it shows the addr finally? why cout reference display its addr, fainting...
It doesn't show the address. It shows the value. The value it shows may well be it's own address, since references are often implemented as pointers under-the-hood, and the referenced object may well occupy the same memory as the reference that was fed to show.
In other words, the memory that is being interpreted as an int via the reference is being reused, and when you access it via the reference you get a value that isn't what you would expect because of that reuse.
and i code
1 2 3
int x = 10;
int& xx = x;
std::cout << xx;
it shows the value, what's differences? won't it because the function passing?
The difference is that xx is an alias for a valid object. In mine (and your original code,) it is not. It may appear to work, but it isn't actually "working."
An object of type std::string keeps its data in dynamically allocated memory, Only some auxiliary data are kept in the stack. So then the control exits the function the destructor of class std::string is called which deletes data in the heap.
std::string s = rr(); // the destructor was called.
In the second example variable h totally is allocated in the stack. So exiting the function does not result in destroying the stack. So until stack will be overwritten by some other data or some called function variable h will be present in the stack.
1 2 3 4 5 6 7
int h = 100;
int i = rr(); // the stack was not destroyrd
However such a behavior is undefined because in general case you can not guarantee that stack will not be rewritten by some other data, function, or thread.