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

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

Closed
apivovarov opened this issue May 21, 2020 · 4 comments
Closed

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

apivovarov opened this issue May 21, 2020 · 4 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@apivovarov
Copy link

apivovarov commented May 21, 2020

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();
}
@nlohmann
Copy link
Owner

With the current code, you make a copy of the stored string and hence return a temporary.

Do this instead:

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

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label May 22, 2020
@apivovarov
Copy link
Author

Looks like get_ref type should be const std::string&. My GetName method is actually const method const char* GetName(int id) const

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

@nlohmann
Copy link
Owner

Ok, does this fix the issue for you?

@apivovarov
Copy link
Author

Yes, Thank you for your help!

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