Note that there are some explanatory texts on larger screens.

plurals
  1. POClass imitating a "pointer to a reference" can save out of scope variables?
    primarykey
    data
    text
    <p>I thought of a strange cheat in C++. Normally, I can't smuggle a reference out of a scope because I can't define an uninitialized reference in the containing scope. However, I can define a pointer to a class containing a reference, fail to initialize it, and then assign it the address of some dynamic memory initialized to a local variable. Even though that dynamic object contains a reference to a variable that is supposed to go out of scope, the pointed-to object still has a valid reference with the same value! g++ doesn't complain even if I tell it to be <code>-pedantic</code>, so I assume it's valid. But how, and why?</p> <pre><code>struct int_ref { int &amp;x; int_ref(int &amp;i): x(i) {} }; #include &lt;iostream&gt; using namespace std; int main(void) { int_ref *irp; int i = 1; int_ref a(i); // Creates an int_ref initialized to i irp = &amp;a; // irp is now a pointer to a reference! // Prints 1 cout &lt;&lt; "irp-&gt;x = " &lt;&lt; irp-&gt;x &lt;&lt; " (i = " &lt;&lt; i &lt;&lt; ")" &lt;&lt; endl; i = 2; // Prints 2 cout &lt;&lt; "irp-&gt;x = " &lt;&lt; irp-&gt;x &lt;&lt; " (i = " &lt;&lt; i &lt;&lt; ")" &lt;&lt; endl; int j = 3; int_ref b(j); irp = &amp;b; // Prints 3 cout &lt;&lt; "irp-&gt;x = " &lt;&lt; irp-&gt;x &lt;&lt; " (i = " &lt;&lt; i &lt;&lt; ", j = " &lt;&lt; j &lt;&lt; ")" &lt;&lt; endl; i = 1; // Still prints 3 cout &lt;&lt; "irp-&gt;x = " &lt;&lt; irp-&gt;x &lt;&lt; " (i = " &lt;&lt; i &lt;&lt; ", j = " &lt;&lt; j &lt;&lt; ")" &lt;&lt; endl; { int k = 4; irp = new int_ref(k); // k goes out of scope } int k = 1; // Doesn't affect the other k, of course // Prints 4 ?! cout &lt;&lt; "irp-&gt;x = " &lt;&lt; irp-&gt;x &lt;&lt; " (i = " &lt;&lt; i &lt;&lt; ", j = " &lt;&lt; j &lt;&lt; ")" &lt;&lt; endl; } </code></pre> <p><strong>Edit:</strong> This may in fact be (as suggested in the answers) an undiagnosed dangling reference. What about if I define <code>int_ref</code> like this:</p> <pre><code>struct int_ref { const int &amp;x; int_ref(const int &amp;i): x(i) {} }; </code></pre> <p>A <code>const</code> reference need not refer to an lvalue, so there is no well-defined concept of a dangling one. Is the code still undefined?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload