-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
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
Getter is setting the value to null if the key does not exist #754
Comments
Closing this since the documentation already recommends at() vs. operator[], although this definitely is unexpected behavior.
|
Note this behavior is exactly the one of #include <map>
#include <iostream>
int main(int argc, char const *argv[])
{
std::map<std::string, int> m;
m["xxx"] = 1;
auto y = m["yyy"];
for (auto i = m.begin(); i != m.end(); ++i)
{
std::cout << i->first << " : " << i->second << std::endl;
}
} produces:
The note you cited refers to the case when we access a const object. Then, |
Thanks for your comment. I wonder why std::map behaves this way. It is counterintuitive to set the value to null or 0 when the key is missing. |
Because if it didn't, then |
Hi, I am puzzled by the answer given to this issue. In the readme there are a ton of sexy examples using a json variable as a map. They look indeed great, but then you are saying here "if you follow the sexy syntax we claim to have in the readme then you will run into undefined behaviour when one day you'll ask for a non-existent key. You should not follow the sexy syntax we show and access elements with an .at() function" ??? Either the readme should show .at() examples or [ ] should be a little bit safer no ? Am I missing sth ? |
There is already a note, see https://github.com/nlohmann/json/blob/develop/README.md#notes. |
Here is the sample code
The output is
{"xxx":1,"yyy":null}
.The expected behavior is to throw std::out_of_range exception
The text was updated successfully, but these errors were encountered: