Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It isn't that an address can't be taken (the compiler could always order it shoved on the stack, which it does with ref-to-const), it's a question of programmers intent. With an interface that takes a A&amp;, it is saying "I will modify what is in this parameter so you can read after the function call". If you pass it a temporary, then the thing it "modified" doesn't exist after the function. This is (probably) a programming error, so it is disallowed. For instance, consider:</p> <pre><code>void plus_one(int &amp; x) { ++x; } int main() { int x = 2; float f = 10.0; plus_one(x); plus_one(f); cout &lt;&lt; x &lt;&lt; endl &lt;&lt; f &lt;&lt; endl; } </code></pre> <p>This doesn't compile, but if temporaries could bind to a ref-to-non-const, it would compile but have surprising results. In plus_one(f), f would be implicitly converted to an temporary int, plus_one would take the temp and increment it, leaving the underlying float f untouched. When plus_one returned, it would have had no effect. This is almost certainly not what the programmer intended.</p> <hr> <p>The rule does occasionally mess up. A common example (described <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1690.html" rel="noreferrer">here</a>), is trying to open a file, print something, and close it. You'd want to be able to do:</p> <pre><code>ofstream("bar.t") &lt;&lt; "flah"; </code></pre> <p>But you can't because operator&lt;&lt; takes a ref-to-non-const. Your options are break it into two lines, or call a method returning a ref-to-non-const:</p> <pre><code>ofstream("bar.t").flush() &lt;&lt; "flah"; </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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