-
-
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
Accessing strings (for example in keys or values) without having the lib create a copy of it. #1916
Comments
Can you provide an example? I currently do not know what you mean exactly.
|
I feel ya, aguaviva. If we ask for, say, json_var["name"] we would get a new JSON object, converted to a string. |
How about using |
Would that not create a copy of an std::string when we try to use it as a string? |
Correct. The following code is one way to test it (live example): Note: Per documentation, writing data to the returned pointer is discouraged. Take following code just as a demonstration. #include "json.hpp"
#include <iostream>
int main() {
nlohmann::json j;
j["key"] = "hello";
auto p1 = j["key"].get_ptr<std::string *>();
auto p2 = j["key"].get_ptr<std::string *>();
std::cout << "Addresses: " << p1 << "," << p2 << std::endl;
std::cout << "Original: " << j["key"].get<std::string>() << "," << *p1 << ","
<< *p2 << std::endl;
*p1 += "1";
std::cout << "Change p1: " << j["key"].get<std::string>() << "," << *p1 << ","
<< *p2 << std::endl;
*p2 += "2";
std::cout << "Change p2: " << j["key"].get<std::string>() << "," << *p1 << ","
<< *p2 << std::endl;
return 0;
} Typical output:
|
Hmm, that works for me! Thanks
Not sure about the OP, their needs might be different.
… |
@nlohmann any chance that we could have |
|
why not make an operator overload to get json::operator[] return a std::string? |
For several reasons:
|
Alright, thanks for the explanation and for such a good lib :)
…On Sun, Feb 9, 2020 at 10:15 AM Niels Lohmann ***@***.***> wrote:
For several reasons:
- The type of the string is templated. It is std::string by default,
but it could be another type. That's why the get_ptr and get_ref
functions are do delicate as they allow you to dig into the JSON type which
may lead to problems.
- What happens if you write std::string& mystring = myjson["foo"], but
myjson["foo"] is an integer?
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
<#1916?email_source=notifications&email_token=ABHVYEZWJUNTAOB4OFA42P3RB7CRRA5CNFSM4KNEETO2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOELGG3WY#issuecomment-583822811>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ABHVYE3AWEX7X4KMHXFZBBLRB7CRRANCNFSM4KNEETOQ>
.
|
I am ok with just having a "const char *" of the string.
I have tried several times an I haven;t had any luck, all I get are copies.
The text was updated successfully, but these errors were encountered: