Skip to content

Question: return static json object from function #618

Closed

Description

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 ?

Activity

  1. Bosswestfalen commented on Jun 14, 2017

    @Bosswestfalen

    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

  2. nlohmann commented on Jun 16, 2017

    @nlohmann
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions