Reputation: 13461
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?
Upvotes: 18
Views: 1008
Reputation: 1
yes it is safe to pass reference through function because in the changes always made in the arguments which you pass by value and in the above code string temps for both A and B will survive until the end of the 'sequence point' that is the semicolon but in case of pass by reference the changes made in copy of that argument not in a original copy.
Upvotes: 0
Reputation: 19443
Is it guaranteed that the temporary string object is not destroyed too soon
For your specific case yes, BUT for the following code no
int main() {
const string &tempString(min("A", "B"));
cout << tempString;
}
Beside that I agree with what "Mike Seymour" said.
Upvotes: 1
Reputation: 254621
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.
Upvotes: 29
Reputation: 35438
Your temporary objects will stay "alive" till the end of the ;
from the cout
in main, so this way of using it is safe.
Upvotes: 4
Reputation: 2908
Yes, it's safe. The string temps for both "A" and "B" will survive until the end of the 'sequence point', that is the semicolon.
Upvotes: 2