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

Question: return static json object from function #618

Closed
ghost opened this issue Jun 13, 2017 · 2 comments
Closed

Question: return static json object from function #618

ghost opened this issue Jun 13, 2017 · 2 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@ghost
Copy link

ghost commented Jun 13, 2017

Hi,
forgive me but I'm a newbie with c++ in general.

I'm trying to use this library but I have a problem.
I have a file like this:

static json config;

json get_config()
{
   config["value"] = 456;
   return config;
}

void save_config()
{
   std::ofstream fout("config.txt");
   fout << std::setw(3) << config << std::endl;
}

in another file I do something like ...

auto obj = get_config();
obj["value"] = 123;
save_config();

but inside config.txt i still see old value (456).
How can I solve this ?

@Bosswestfalen
Copy link

Hi,

assuming the first code block is in file A and the second block is in file B.
When you call save_config() from file B the function uses the config object from file A, because you do not
pass an argument to the function. The function in file A does not know about the object from file B.

There are two ways to solve this problem, depending on what you want to do.
If you want to modify the static object make get_config() return a reference.
If you want to make a copy of the static object (that is what happens now) and store it, pass it to save_config.

Regards,
Bosswestfalen

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Jun 14, 2017
@nlohmann
Copy link
Owner

@bdoblackfish Did this work for you?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

2 participants