Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing r values by reference?

I frequently write functions that take arguments by non-const reference, but the downside is that I can't pass r-values.

A colleague of mine showed me this piece of code which supposedly solves the problem:

#include <iostream>

// example function
int f(int& x) {
    x += 5;
    return x;
}

// is this undefined behaviour?
auto& to_l_value(auto&& x) {
    return x;
}

int main () {
    auto y = f(to_l_value(5)); // usage example
    std::cout << y; // 10
    return 0;
}

Is this undefined behaviour because of a dangling reference? (does 5 get destroyed before f is called?)

When does the temporary get destroyed?

like image 227
SomeProgrammer Avatar asked Sep 13 '21 15:09

SomeProgrammer


Video Answer


1 Answers

Temporaries are destroyed (except some exceptions) when full expression is finished. So you are fine here.

More details about lifetime:

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.

There are two exceptions from that:

  • The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.
  • The lifetime of a temporary object created when evaluating the default arguments of a default or copy constructor used to initialize an element of an array ends before the next element of the array begins initialization.
like image 195
Jarod42 Avatar answered Sep 30 '22 13:09

Jarod42