0

Will returning by const lvalue reference extend lifetime of variable? If I had this code

const int& refer()
{
    int x = 2938;
    return x;
}
int main()
{
    const int& catcher = refer();
    return 0;
}

Would the lifetime of variable x be extended to match the lifetime of the reference catcher? Just like extending the lifetime of a temporary (rvalue) using a const lvalue reference?

hnefatl
  • 5,860
  • 2
  • 27
  • 49
  • 1
    This has been asked a lot on this site. The answer is "no". It will not extend the lifetime of a variable that goes out of scope. A reference can only extend the lifetime of a temporary variable in the current scope. – Nikos C. Feb 04 '18 at 12:22
  • @NikosC. thank you for the input. Regarding the duplicate, isn't that question only convering non-const lvalue references, whereas my question is focusing on const lvalue references? I mean, the rules are different for these two types of references... For instance, a non-const lvalue reference won't extend the lifetime of a temporary anyway, right.. –  Feb 04 '18 at 12:26
  • The `const` has no impact on the lifetime of variables. – Nikos C. Feb 04 '18 at 12:27
  • 2
    @asd BTW I found the dupe in a second, entering your exact question title in google. –  Feb 04 '18 at 12:27
  • @NikosC. are you sure? From what i know, only const references can expand the lifetime of temporaries as [see](https://stackoverflow.com/a/2784304/9224744) or am I misunderstanding something. If this is true, there must be a difference between const and non-const lvalue references when it comes to the topic of lifetime extension. –  Feb 04 '18 at 12:30
  • The `const` in this case is needed to be able to create the reference at all. It's not because of lifetime, it's because you can't bind a non-const reference to an rvalue. And the reason for that is that the standard is trying to prevent you from modifying the value of a temporary by accident. Has nothing to do with lifetime. – Nikos C. Feb 04 '18 at 12:38
  • @NikosC. Got it. Thanks :) –  Feb 04 '18 at 12:40

0 Answers0