Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy not non-const reference to temporary objects?
    primarykey
    data
    text
    <p>C++ allows assignment of temporary objects only to const reference. It wont allow assignement of temporary objects to reference.</p> <p>For example: </p> <pre><code>String&amp; a = String("test"); // Error const String&amp; a = String("test"); // Ok </code></pre> <p>Everywhere I google for this result, i only see the following answers</p> <ol> <li>Modifying temporary objects would cause unidentifiable problems</li> <li>Modifying temporary objects is dangerous</li> <li>At some point of time, you will forget it is a temporary variable</li> </ol> <p>It's been said, temporary objects vanishes after the statement. So you should not modify it.</p> <p>If C++, is so keen in blocking modifying the temporary objects, it should have blocked reading the temporary objects right? If the temporary object is vanished, then there is no point in reading contents from there right? The possible cases, where a right can occur, could also involve the read too.</p> <p>Then why its been blocking write alone and allowing read? </p> <p>Please give me a solid c++ code explanation.</p> <p>Please dont deviate the question by pointing some alternatives. Please give me solid answer with code why const int &amp; is allowed and int &amp; is not allowed for temporary objects.</p> <p>One says &amp;&amp; is there.. My question different.. ANother say,changing will not reflect.. Changing will not reflect even when it is const int &amp; too. Eg: double a; Const int &amp; i = a; a++; will not affect i..</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    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