File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -2623,6 +2623,30 @@ int main(void) {
26232623}
26242624```
26252625
2626+
2627+ * Example 4: Value capture with `std::string_view` instances
2628+
2629+ ```cpp
2630+ void example() {
2631+ ondemand::parser parser;
2632+ const padded_string json = R"({ "parent": {"child1": {"name": "John"} , "child2": {"name": "Daniel"}} })"_padded;
2633+ auto doc = parser.iterate(json);
2634+ ondemand::object parent = doc["parent"];
2635+ // parent owns the focus
2636+ ondemand::object c1 = parent["child1"];
2637+ // c1 owns the focus
2638+ //
2639+ std::string_view as1 = c1["name"];
2640+ // We have that as1 == "John", as long as 'parser' and 'json' live
2641+ // c2 attempts to grab the focus from parent but fails
2642+ ondemand::object c2 = parent["child2"];
2643+ // c2 owns the focus, at this point c1 is invalid
2644+ std::string_view as2 = c2["name"];
2645+ // We have that as2 == "Daniel", as long as 'parser' and 'json' live
2646+ std::cout << as1 << " " << as2 << std::endl; // prints John Daniel
2647+ }
2648+ ```
2649+
26262650Performance tips
26272651--------
26282652
Original file line number Diff line number Diff line change @@ -1557,6 +1557,29 @@ bool allow_comma_separated_example() {
15571557 }
15581558 TEST_SUCCEED ();
15591559}
1560+
1561+ bool issue2215 () {
1562+ TEST_START ();
1563+ ondemand::parser parser;
1564+ const padded_string json = R"( { "parent": {"child1": {"name": "John"} , "child2": {"name": "Daniel"}} })" _padded;
1565+ auto doc = parser.iterate(json);
1566+ ondemand::object parent = doc[" parent" ];
1567+ // parent owns the focus
1568+ ondemand::object c1 = parent[" child1" ];
1569+ // c1 owns the focus
1570+ //
1571+ std::string_view as1 = c1[" name" ];
1572+ // We have that as1 == "John", as long as 'parser' and 'json' live
1573+ // c2 attempts to grab the focus from parent but fails
1574+ ondemand::object c2 = parent[" child2" ];
1575+ // c2 owns the focus, at this point c1 is invalid
1576+ std::string_view as2 = c2[" name" ];
1577+ // We have that as2 == "Daniel", as long as 'parser' and 'json' live
1578+ ASSERT_EQUAL (as1, " John" );
1579+ ASSERT_EQUAL (as2, " Daniel" );
1580+ std::cout << as1 << " " << as2 << std::endl;
1581+ TEST_SUCCEED ();
1582+ }
15601583#endif
15611584bool test_load_example () {
15621585 TEST_START ();
@@ -1918,6 +1941,7 @@ bool run() {
19181941 && current_location_no_error ()
19191942 && to_string_example_no_except ()
19201943 #if SIMDJSON_EXCEPTIONS
1944+ && issue2215 ()
19211945 && to_string_example ()
19221946 && raw_string ()
19231947 && number_tests ()
You can’t perform that action at this time.
0 commit comments