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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With