title: C++ references and transient objects
body: <p>I am currently working on a particular embedded system (in C++), which doesn't have much memory in it. Hence, using new/delete is out of the question. I do have some of my memory management system set up, however, I am exploring some other ways to solve certain problems (not exactly related to memory management, but that is really not important here). While searching, a rather simple question popped up, still I am not 100% sure about the answer, so I'd like to hear from experts on this one.</p>
  
  <p>My question in the end is actually about references in C++, as well as how exactly transient objects function.</p>
  
  <pre><code>class Obj
  {
      // id is automatically set, starting from 1, step by 1
      public: const int id = ...;
  
          // other unrelated stuff in the class
  };
  
  class Test
  {
      public: Obj&amp; obj;
      public: Test(Obj&amp;&amp; o) : obj(o) { }
  };
  
  void test()
  {
      Obj o1; // id is 1
      Obj o2; // id is 2
  
      Test t = Obj(); // [*] id of this transient obj is 3
  
      cout &lt;&lt; t.obj.id &lt;&lt; endl; // prints 3, as expected?
  }
  </code></pre>
  
  <p>I know that rvalue references are lvalues (since they are named objects, and named objects are always lvalues), hence the Test class is okay and has no errors (compile errors). However, the transient object Obj() (marked with *), as far as I know, should be destroyed after ; on the same line, so the test object 't' afterwards should have an invalid reference to a destroyed object, if I am correct. And the 3 printing is actually unexpected behavior, yet accidental that it still has 3 written in it's memory location which I am accessing while printing it out. Is this what is actually happening, or is there something else that I am lacking to see/know? Isn't there some kind of mechanism to detect such situation and prolong/extend the lifetime of the object until the one referencing it is destroyed as well (in this example, prolong the lifetime of Obj() until the end of the function test(), when the 't' gets destroyed)?</p>