Skip to content

Is it safe to return string.c_str() received from get()? #2130

Description

@apivovarov

What do you want to achieve?

I'm building a function const char* GetName(id).

Data is stored in json file, e.g. [{"name":"N1"}, {"name":"N2"}, {"name":"N3"}]

Is it safe for my function to return c_str pointers from std::string received from get()? I'm not sure about std::string objects lifecycle inside nlohmann::json.

Example:

nlohmann::json metadata;  // will be alive till the end of the program
jsonFile >> metadata;

const char* GetName(int id) {
  return metadata[id]["name"].get<std::string>().c_str();
}

Activity

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