mirror of
https://github.com/nlohmann/json.git
synced 2026-10-10 08:27:13 +00:00
Delete json_document::root() on temporary documents
auto v = json_document::parse(text).root() compiled and left the view dangling. Delete the overload for rvalue documents, take a named document in the tests, and document the lifetime rule. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
4 files changed
+80
-22
No files matched your search
@@ -1,10 +1,15 @@
|
||||
# <small>nlohmann::basic_json_document::</small>root
|
||||
|
||||
```cpp
|
||||
view_type root() const noexcept;
|
||||
// (1)
|
||||
view_type root() const& noexcept;
|
||||
|
||||
// (2)
|
||||
view_type root() const&& = delete;
|
||||
```
|
||||
|
||||
Returns a view of the root value of the document.
|
||||
1. Returns a view of the root value of the document.
|
||||
2. Deleted: the view of a temporary document would dangle.
|
||||
|
||||
## Return value
|
||||
|
||||
@@ -21,6 +26,16 @@ Constant.
|
||||
|
||||
## Notes
|
||||
|
||||
**Lifetime.** A view refers into the document, so the document must outlive it. `root()` can therefore only be called
|
||||
on a document that has a name (an lvalue); calling it on a temporary does not compile:
|
||||
|
||||
```cpp
|
||||
auto v = json_document::parse(text).root(); // error: the document is destroyed at the end of the statement
|
||||
|
||||
auto doc = json_document::parse(text); // OK: keep the document alive
|
||||
auto v = doc.root();
|
||||
```
|
||||
|
||||
`root()` is a cheap handle into the document's index, not a copy of anything; call it as often as needed. The
|
||||
returned view is valid under the same conditions as any other view of the document -- see
|
||||
[Object inspection](../basic_json_view/index.md) -- in particular, it is invalidated by the next
|
||||
|
||||
@@ -76,6 +76,9 @@ Moving the document itself is fine and does **not** invalidate its views: the in
|
||||
that keeps its address across the move. Take a fresh view from [`root()`](../api/basic_json_document/root.md)
|
||||
whenever any of the other conditions above was not met.
|
||||
|
||||
Because a view dies with its document, [`root()`](../api/basic_json_document/root.md) is not callable on a temporary
|
||||
document: `#!cpp auto v = json_document::parse(text).root();` does not compile. Give the document a name first.
|
||||
|
||||
??? example "Example: borrowed and owned documents, and when views become invalid"
|
||||
|
||||
```cpp
|
||||
|
||||
Reference in new issue
Block a user