nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
42.38k stars 6.67k forks source link

Copying ctor and moving ctor null ordered_json corrupts it (mingw 8) #4164

Open matejk opened 1 year ago

matejk commented 1 year ago

Description

Creating a copy of null JSON with copy ctor or moving it with move ctor corrupts it.

Type turns into array and that array contains one null element.

Null JSON is properly copied when using assignment operator.

I use the library from "include.zip".

Reproduction steps

See example below.

Expected vs. actual results

Copied null JSON shall still be null JSON and does not turn into something different.

Minimal code example

// A google test function demonstrating the problem.
TEST(Parameters, JsonCopyCtor)
{
    nlohmann::ordered_json null_json;

    std::cout << null_json.dump() << std::endl;
    EXPECT_TRUE(null_json.is_null());

    const auto json_copy { null_json };

    std::cout << json_copy.dump() << std::endl;
    EXPECT_TRUE(json_copy.is_null());
    EXPECT_FALSE(json_copy.is_array());

    const auto json_copy_2 = null_json ;

    std::cout << json_copy_2.dump() << std::endl;
    EXPECT_TRUE(json_copy_2.is_null());
    EXPECT_FALSE(json_copy_2.is_array());

    const auto json_copy_3 { std::move(null_json) } ;

    std::cout << json_copy_3.dump() << std::endl;
    EXPECT_TRUE(json_copy_3.is_null());
    EXPECT_FALSE(json_copy_3.is_array());
}

Error messages

Output from Google test:

[ RUN      ] Parameters.JsonCopyCtor
null
[null]
C:/Users/m.kenda/workspace/ConfigSerializer.cpp:78: Failure
Value of: json_copy.is_null()
  Actual: false
Expected: true
C:/Users/m.kenda/workspace/ConfigSerializer.cpp:79: Failure
Value of: json_copy.is_array()
  Actual: true
Expected: false
null
[null]
C:/Users/m.kenda/workspace/ConfigSerializer.cpp:90: Failure
Value of: json_copy_3.is_null()
  Actual: false
Expected: true
C:/Users/m.kenda/workspace/ConfigSerializer.cpp:91: Failure
Value of: json_copy_3.is_array()
  Actual: true
Expected: false
[  FAILED  ] Parameters.JsonCopyCtor (0 ms)

Compiler and operating system

MinGW 8.1, Windows 10

Library version

3.11.2

Validation

nlohmann commented 1 year ago

This is a know issue: compilers treat {} differently. With

const auto json_copy { null_json };

you create an array.

Use

const auto json_copy_2 = null_json ;

instead.