1 // __ _____ _____ _____ 2 // __| | __| | | | JSON for Modern C++ (supporting code) 3 // | | |__ | | | | | | version 3.11.3 4 // |_____|_____|_____|_|___| https://github.com/nlohmann/json 5 // 6 // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me> 7 // SPDX-License-Identifier: MIT 8 9 #include "doctest_compatibility.h" 10 11 #include <nlohmann/json.hpp> 12 #include <exception> 13 #include <iostream> 14 15 struct Foo 16 { 17 int a; 18 int b; 19 }; 20 21 namespace nlohmann 22 { 23 template <> 24 struct adl_serializer<Foo> 25 { to_jsonnlohmann::adl_serializer26 static void to_json(json& j, Foo const& f) 27 { 28 switch (f.b) 29 { 30 case 0: 31 j["a"] = f.a; 32 break; 33 case 1: 34 j[0] = f.a; 35 break; 36 default: 37 j = "test"; 38 } 39 if (f.a == 1) 40 { 41 throw std::runtime_error("b is invalid"); 42 } 43 } 44 }; 45 } // namespace nlohmann 46 47 TEST_CASE("check_for_mem_leak_on_adl_to_json-1") 48 { 49 try 50 { 51 const nlohmann::json j = Foo {1, 0}; 52 std::cout << j.dump() << "\n"; 53 } 54 catch (...) // NOLINT(bugprone-empty-catch) 55 { 56 // just ignore the exception in this POC 57 } 58 } 59 60 TEST_CASE("check_for_mem_leak_on_adl_to_json-2") 61 { 62 try 63 { 64 const nlohmann::json j = Foo {1, 1}; 65 std::cout << j.dump() << "\n"; 66 } 67 catch (...) // NOLINT(bugprone-empty-catch) 68 { 69 // just ignore the exception in this POC 70 } 71 } 72 73 TEST_CASE("check_for_mem_leak_on_adl_to_json-2") 74 { 75 try 76 { 77 const nlohmann::json j = Foo {1, 2}; 78 std::cout << j.dump() << "\n"; 79 } 80 catch (...) // NOLINT(bugprone-empty-catch) 81 { 82 // just ignore the exception in this POC 83 } 84 } 85 86 87