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

Ternary operator crash #1034

Closed
parfenuk opened this issue Apr 2, 2018 · 3 comments
Closed

Ternary operator crash #1034

parfenuk opened this issue Apr 2, 2018 · 3 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@parfenuk
Copy link

parfenuk commented Apr 2, 2018

This simple code crashes:
string someStr;
json j = json::object();
// the next line crashes
j["someKey"] = someStr.empty() ? nullptr : someStr;

However, if I use standard if-else condition, everything is fine:
string someStr;
json j = json::object();
// the code below works ok
if (someStr.empty()) j["someKey"] = nullptr;
else j["someKey"] = someStr;

Also if S is not empty - both versions work.
Is it a bug or feature? :)

I'm using GNU C++ 14 compiler, IDE Xcode 9.3

@nlohmann
Copy link
Owner

nlohmann commented Apr 2, 2018

The types in someStr.empty() ? nullptr : someStr seems to be treated as const char* then yields j["someKey"] = (const char*)nullptr; which calls std::string(nullptr) which yields the error.

I have no idea how to tell the compiler that someStr.empty() ? nullptr : someStr should be treated as json other than to make it explicit:

j["someKey"] = someStr.empty() ? json(nullptr) : json(someStr);

@gregmarr
Copy link
Contributor

gregmarr commented Apr 2, 2018

A single type is deduced based on the types of the two values of the ternary operator. There is no type that works properly for nullptr and std::string here. That requirement is not there for the if/else. If you want the type to be null for an empty someStr instead of an empty string, you need to use the if/else. Otherwise, there's no point in even having the check, and you can simply do j["someKey"] = someStr;.

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Apr 2, 2018
@parfenuk
Copy link
Author

parfenuk commented Apr 2, 2018

Yes, I indeed need the field being null for empty strings, and I was able to solve it.
Thank you, guys, for telling me two different solutions and for an information about how ternary operator works.

@parfenuk parfenuk closed this as completed Apr 2, 2018
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

3 participants