-
-
Notifications
You must be signed in to change notification settings - Fork 6.7k
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
Suggestion to improve value() accessors with respect to move semantics #1275
Comments
One more thing: it may also be useful to provide r-value reference overload to the conversion Currently, this doesn't do what one might expect: json j{{"x", "123"}};
std::string val = std::move(j["x"]);
// oops, j["x"] still has the value "123" - we just copied stuff even though wanted to move
// we have to do this to make it work, cumbersome
std::string val = std::move(j["x"].get_ref<std::string&>()); |
+1 on the first point. Forwarding reference definitely makes sense there. I don't agree on the second one. I could see an argument for it to return a "ValueType&&", but returning a "ValueType" with a side-effect of changing the underlying json object feels "surprising" to me (and I don't like surprises in interfaces :)). |
You can't return |
I wrote "ValueType&&" as shorthand, sorry for being imprecise. I meant that it really should be returning rvalue in all cases (aka, You could solve this by adding additional overloads to trap those, but then you get very different behavior depending on what type your second argument is, and that is also a "surprising" API to me. All in all, I like the spirit of your (2) suggestion, but I don't see a way to get all the benefits without adding surprises too. The idea that a function named "value(key,def)&&" has side effects is surprising to me as a code-maintainer. If you rename your function to "pop_value(key,def)&&" that returns value type (exactly as you proposed), then I am totally on board. |
I like the original proposal from @murderotica. Could you provide a PR? |
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
Reopened due to bug found. See #2181. |
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
Here's a couple suggestions that I think might be worth adding to improve the usage of value() function:
&&
instead ofconst&
fordefault_value
to lift a problem thatconst ValueType& default_value
inhibits move whendefault_value
is temporary/r-value:Before:
After
This will allow this:
value()
to allow moving from JSON's values when JSON is temporary/r-value:This will make possible the following:
The text was updated successfully, but these errors were encountered: