2

While debugging an application I came up with the following example:

#include <nlohmann/json.hpp>

using nlohmann::json;
struct X {
    X(const std::string& s){}
};
int main() {
    X x("{}"_json); // why compiler allows this?
}

See at Godbolt

Could someone explain this? Is this a bug or an unexpected side effect of nlohmann/json library?


Update:

... and here is the second question:

As implicit to_string conversion is a documented feature, then is this a bug that this even simpler example fails at runtime?

#include <nlohmann/json.hpp>
using nlohmann::json;
int main() {
  std::string j = "{}"_json;  
}

terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_2::detail::type_error' what(): [json.exception.type_error.302] type must be string, but is object

1 Answers1

2

If you look up API docs here: https://github.com/nlohmann/json/search?q=operator+string

You'll find that operator string_t() is a documented feature of the library to convert json_pointer to string_t. This conversion is considered when you call the ctor of X with an argument type that's not the listed argument type (const std::string&) and likely succeeds (to the extent that it can be compiled).

lorro
  • 10,687
  • 23
  • 36
  • 1
    That operator is deprecated though, but it as [`operator ValueType ()`](https://json.nlohmann.me/api/basic_json/operator_ValueType/) that may play a role here. Edit: Hmm, nope, that doesn't seem to be it either... – Ted Lyngmo Dec 20 '22 at 23:07
  • Another question then why this implicit conversion fails ? (See error at Godbolt link) – Dmitriy Kumshayev Dec 20 '22 at 23:28
  • Basically event just this line will compile and then fail at runtime: std::string j = "{}"_json; – Dmitriy Kumshayev Dec 20 '22 at 23:42