Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is passing a reference through function safe?

Tags:

c++

c++11

Is the following function safe in C++03 or C++11 or does it exhibit UB?

string const &min(string const &a, string const &b) {
    return a < b ? a : b;
}

int main() {
    cout << min("A", "B");
}
  • Is it OK to return a reference to an object passed to the function by reference?

  • Is it guaranteed that the temporary string object is not destroyed too soon?

  • Is there any chance that the given function min could exhibit UB (if it does not in the given context)?

  • Is it possible to make an equivalent, but safe function while still avoiding copying or moving?

like image 291
Juraj Blaho Avatar asked Apr 29 '13 13:04

Juraj Blaho


People also ask

What will happen when a function is using pass by reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.

Is passing by reference good?

Passing value objects by reference is in general a bad design. There are certain scenarios it's valid for, like array position swapping for high performance sorting operations. There are very few reasons you should need this functionality. In C# the usage of the OUT keyword is generally a shortcoming in and of itself.

What is a disadvantage of passing by reference?

The major disadvantages of using call by reference method are a follows: A function taking in a reference requires ensuring that the input is non-null. Thus, a null check is not supposed to be made. Thus, it has a non-null guarantee. Further, passing by reference makes the function not pure theoretically.

Does passing by reference make a copy?

pass-by-reference does not make any copy, it gets the reference of the object itself by just renaming it, so no any copying operation.


1 Answers

Is it OK to return a reference to an object passed to the function by reference?

As long as the object isn't destroyed before you access it via that reference, yes.

Is it guaranteed that the temporary string object is not destroyed too soon?

In this case, yes. A temporary lasts until the end of the full expression which creates it, so it is not destroyed until after being streamed to cout.

Is there any chance that the given function min could exhibit UB (if it does not in the given context)?

Yes, here is an example:

auto const & r = min("A", "B"); // r is a reference to one of the temporaries
cout << r;                      // Whoops! Both temporaries have been destroyed

Is it possible to make an equivalent, but safe function while still avoiding copying or moving?

I don't think so; but this function is safe as long as you don't keep hold of a reference to its result.

like image 71
Mike Seymour Avatar answered Sep 30 '22 19:09

Mike Seymour