-
Notifications
You must be signed in to change notification settings - Fork 68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
optional<const string &>::value_or returns reference to temp #68
Comments
Thanks for the report. My apologies for keeping it waiting for a month. Yes, Taking only |
As far as I can understand, in the second line of code, You are storing std::string object into boost::optional<string&> object which is causing the problem.
|
Sure, that would prevent UB here but at the cost of an extra string copy, which I was trying to avoid. If |
I'm using
boost::optional<const string &>
and found some pitfalls when usingvalue_or(char *)
.Basically since
value_or
takes the "or" party as a template type the conversion fromchar *
tostring
happens inside the function call and then a reference to that temporary is returned, leading to UB and in my case a crash.Furthermore, even if the optional is populated and the alternative isn't use, it seems that some sort of copy of the value is still required because of the use of the
?:
and then a similar crash occurs.I think a reasonable workaround would be to have the
value_or
for references take the alternative value (r
) only asconst T &
instead of as a type param. This would require the implicit conversion to happen at the call site and the function would not create a temporary.This doesn't avoid all possible dangling references but it improves things.
Here is a short reproduction. I'm using boost 1.69, gcc 8.2:
Note I do get a warning about returning a reference to a temporary. But usually we disable warnings within boost because there's so much noise.
The text was updated successfully, but these errors were encountered: