What happens when C++ reference leaves it's scope?
<p>If I interpret C++ references correctly, they are like pointers, but with guaranteed data integrity (no NULL, no (int*) 0x12345). But what happens when scope of referenced object is leaved? If there are no magic involved (and probably it is not), referenced object will be destroyed behind my back. </p>

<p>I wrote a piece of code to check this:</p>

<pre><code>#include &lt;iostream&gt;
using namespace std;

class A {
public:
        A(int k) { _k = k; };
        int get() { return _k; };
        int _k;
};

class B {
public:
        B(A&amp; a) : _a(a) {}
        void b() { cout &lt;&lt; _a.get(); }
        A&amp; _a;
};

B* f() {
        A a(10);
        return new B(a);
}

int main() {
        f()-&gt;b();
}
</code></pre>

<p>The <code>_k</code> instance variable was put in to check stack frame existence.</p>

<p>It surprisingly does not segfault and instead prints '10' correctly, while I suppose that <code>A</code> is allocated on stack and that stack frame of <code>f()</code> will be overwritten by at least <code>cout&lt;&lt;</code> call.</p>
