Very simple question, which most likely calls for an explanation on how references work and why my understanding is flawed.
Given the simple code snippet below:
#include <iostream>
#include <string>
struct Foo
{
std::string &ref;
Foo(std::string &bar) : ref(bar) { }
};
int main()
{
std::string s1 = "foo1";
Foo f(s1);
f.ref[0] = 'b';
std::cout << s1 << std::endl; // prints boo1
{
std::string f2("tmp");
f.ref = f2;
}
// shouldn't f.ref be dangling by now?
std::cout << f.ref; // prints tmp
}
Output:
My understanding is that f2 will be destroyed at the end of that block, thus f.ref will be a dangling reference. What is really going on?