1
0
mirror of https://github.com/nlohmann/json synced 2024-11-15 00:31:05 +00:00

Improve json_ref implementation

This commit is contained in:
Alexander Karzhenkov 2020-09-27 10:45:21 +05:00
parent fd7a9f6007
commit 42a9dc0bc3
2 changed files with 12 additions and 28 deletions

View File

@ -17,19 +17,14 @@ class json_ref
json_ref(value_type&& value)
: owned_value(std::move(value))
, value_ref(&owned_value)
, is_rvalue(true)
{}
json_ref(const value_type& value)
: value_ref(const_cast<value_type*>(&value))
, is_rvalue(false)
: value_ref(&value)
{}
json_ref(std::initializer_list<json_ref> init)
: owned_value(init)
, value_ref(&owned_value)
, is_rvalue(true)
{}
template <
@ -37,8 +32,6 @@ class json_ref
enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
json_ref(Args && ... args)
: owned_value(std::forward<Args>(args)...)
, value_ref(&owned_value)
, is_rvalue(true)
{}
// class should be movable only
@ -50,27 +43,26 @@ class json_ref
value_type moved_or_copied() const
{
if (is_rvalue)
if (value_ref == nullptr)
{
return std::move(*value_ref);
return std::move(owned_value);
}
return *value_ref;
}
value_type const& operator*() const
{
return *static_cast<value_type const*>(value_ref);
return value_ref ? *value_ref : owned_value;
}
value_type const* operator->() const
{
return static_cast<value_type const*>(value_ref);
return &**this;
}
private:
mutable value_type owned_value = nullptr;
value_type* value_ref = nullptr;
const bool is_rvalue = true;
value_type const* value_ref = nullptr;
};
} // namespace detail
} // namespace nlohmann

View File

@ -12605,19 +12605,14 @@ class json_ref
json_ref(value_type&& value)
: owned_value(std::move(value))
, value_ref(&owned_value)
, is_rvalue(true)
{}
json_ref(const value_type& value)
: value_ref(const_cast<value_type*>(&value))
, is_rvalue(false)
: value_ref(&value)
{}
json_ref(std::initializer_list<json_ref> init)
: owned_value(init)
, value_ref(&owned_value)
, is_rvalue(true)
{}
template <
@ -12625,8 +12620,6 @@ class json_ref
enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
json_ref(Args && ... args)
: owned_value(std::forward<Args>(args)...)
, value_ref(&owned_value)
, is_rvalue(true)
{}
// class should be movable only
@ -12638,27 +12631,26 @@ class json_ref
value_type moved_or_copied() const
{
if (is_rvalue)
if (value_ref == nullptr)
{
return std::move(*value_ref);
return std::move(owned_value);
}
return *value_ref;
}
value_type const& operator*() const
{
return *static_cast<value_type const*>(value_ref);
return value_ref ? *value_ref : owned_value;
}
value_type const* operator->() const
{
return static_cast<value_type const*>(value_ref);
return &**this;
}
private:
mutable value_type owned_value = nullptr;
value_type* value_ref = nullptr;
const bool is_rvalue = true;
value_type const* value_ref = nullptr;
};
} // namespace detail
} // namespace nlohmann