2

In C++ you cannot initialize a reference from an rvalue because the rvalue is immediately destroyed. How can const references be initialized from rvalues?

For example:

int f() {
    return 3;
}

int main() {
    const int& x = f(); // ok
    int& y = f();       // error: invalid initialization of non-const reference of 
                        // type ‘int&’ from an rvalue of type ‘int’
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
jcarpenter2
  • 5,312
  • 4
  • 22
  • 49
  • What do you mean by initializing reference with rvalue? Can you elaborate? – Shridhar.S Mar 17 '17 at 23:21
  • Here: http://lpaste.net/353657 – jcarpenter2 Mar 17 '17 at 23:23
  • This article explains everything to do with rvalue references: http://thbecker.net/articles/rvalue_references/section_01.html EDIT: Hmm, the article I linked to does not cover `const` r-value references. My mistake. – Dai Mar 17 '17 at 23:23
  • 1
    The lifetime of the temporary is extended when you bind it to a const lvalue reference (or an rvalue reference), see [this](http://en.cppreference.com/w/cpp/language/reference_initialization#Lifetime_of_a_temporary). – Praetorian Mar 17 '17 at 23:25
  • When you bind a const lvalue reference to a prvalue, nothing is getting destroyed... – Kerrek SB Mar 17 '17 at 23:25
  • 1
    " How can const references be initialized from rvalues?" Because the language standard says it can be. Obviously, the implementation must maintain the lifetime of the thing referred to somehow. It's not too difficult to imagine ways of implementing this. –  Mar 17 '17 at 23:36

1 Answers1

-2

If I understand your question correctly, I guess you are wondering how the code "const int& x = f();" works because the return value of f() will get destroyed and the reference to that object is invalid. But note that, the return value of any function is on the stack in a temporary variable thats created by the compiler, so it does stay until the calling function returns and its stack gets destroyed.

Shridhar.S
  • 112
  • 2