Skip to content
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

Local copy given by operator[] or at() #3704

Closed
2 tasks done
mbelhadi opened this issue Aug 15, 2022 · 3 comments
Closed
2 tasks done

Local copy given by operator[] or at() #3704

mbelhadi opened this issue Aug 15, 2022 · 3 comments

Comments

@mbelhadi
Copy link

mbelhadi commented Aug 15, 2022

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

std::string const &value = obj["key"];
// or
std::string const &value = obj.at("key");

Minimal code example

// ...
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

Error messages

No response

Compiler and operating system

gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1)

Library version

develop commit 8fcdbf2

Validation

@falbrechtskirchinger
Copy link
Contributor

falbrechtskirchinger commented Aug 15, 2022

This is as designed and you already figured out that you need to use 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.

@mbelhadi
Copy link
Author

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.

@gregmarr
Copy link
Contributor

FYi, operator[] and at() do return references, it's the implicit conversions to std::string afterwards that convert to a copy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants