We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
Hello,
I have strange behaviour when I try to get a value from a json object.
Just trying de get a reference using operator[] or .at()
I expected the actual reference of a value when I do this
std::string const &value = obj["key"]; // or std::string const &value = obj.at("key");
// ... json obj = {{"key", "value"}}; const std::string &a = obj["key"]; // new local copy of value const std::string &b = obj.at("key"); // new local copy of value const std::string &c = obj.at("key").get_ref<std::string const &>(); // the real ref std::cout << a.c_str() != c.c_str() << std::endl; // false std::cout << b.c_str() != c.c_str() << std::endl; // false
No response
gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1)
develop commit 8fcdbf2
develop
The text was updated successfully, but these errors were encountered:
This is as designed and you already figured out that you need to use get_ref().
get_ref()
operator[] and at() return a basic_json reference which implicitly converts to a copy of and not a reference to the internal value.
operator[]
at()
basic_json
Sorry, something went wrong.
Why do you not send always a reference , and the final variable defines the copy behaviour as STL does.
std::string const &a = obj["key"]; // ref to const ref std::string &b = obj["key"]; // ref to ref std::string c = obj["key"]; // ref to copy
The get or get_ref have a heavy syntax, may be there is a technical limitation for doing this.
Thanks for your answer, closing the issue.
FYi, operator[] and at() do return references, it's the implicit conversions to std::string afterwards that convert to a copy.
No branches or pull requests
Description
Hello,
I have strange behaviour when I try to get a value from a json object.
Reproduction steps
Just trying de get a reference using operator[] or .at()
Expected vs. actual results
I expected the actual reference of a value when I do this
Minimal code example
Error messages
No response
Compiler and operating system
gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1)
Library version
develop commit 8fcdbf2
Validation
develop
branch is used.The text was updated successfully, but these errors were encountered: