Merge pull request #77 from robbert-vdh/feature/nontrivial-variant-deserialization

Avoid reinitializing nontrivial std::variant
This commit is contained in:
Mindaugas Vinkelis
2021-05-29 09:31:51 +03:00
committed by GitHub

View File

@@ -54,6 +54,17 @@ namespace bitsery {
this->execIndex(index, obj, [this, &des](auto& data, auto index) {
constexpr size_t Index = decltype(index)::value;
using TElem = typename std::variant_alternative<Index, std::variant<Ts...>>::type;
// Reinitializing nontrivial types may be expensive especially when they
// reference heap data, so if `data` is already holding the requested
// variant then we'll deserialize into the existing object
if constexpr (!std::is_trivial_v<TElem>) {
if (auto item = std::get_if<TElem>(&data)) {
this->serializeType(des, *item);
return;
}
}
TElem item = ::bitsery::Access::create<TElem>();
this->serializeType(des, item);
data = std::variant<Ts...>(std::in_place_index_t<Index>{}, std::move(item));