Reputation: 502
we use some functions like this:
std::string const & GetValue(std::string const & val) {
return val;
}
Is there a way to break compilation if a user is passing a temporary, because the code is sometimes misused using function calls like the following:
std::string const & abc = GetValue(std::string("Value"));
And is there a difference (regarding the lifetime of the passed object) if the return value is not assigned to a reference, but to an object?
std::string def = GetValue(std::string("Value"));
Thanks a lot!
Upvotes: 1
Views: 56
Reputation: 477040
You could add a deleted rvalue overload to prohibit binding to rvalues entirely:
void GetValue(std::string && val) = delete;
Alternatively, you could make the rvalue overload return a prvalue, thus avoiding dangling references:
std::string GetValue(std::string && val) { return GetValue(val); }
Upvotes: 3