Juraj Blaho
Juraj Blaho

Reputation: 13461

Is passing a reference through function safe?

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");
}

Upvotes: 18

Views: 1008

Answers (5)

Sudhanshu_Saxena
Sudhanshu_Saxena

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

Roee Gavirel
Roee Gavirel

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

Mike Seymour
Mike Seymour

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

Ferenc Deak
Ferenc Deak

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

Scott Jones
Scott Jones

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

Related Questions