Commit 461f0182 authored by Nicholas Ormrod's avatar Nicholas Ormrod Committed by Sara Golemon

Recycle heap on assignment

Summary: For standard containers, assignment tries to reuse heap space.
Dynamic assignment does not - it calls destroy(), and then reconstructs
a new dynamic. In the case that the old and new types are the same (eg
assigning a dynamic-vector to a dynamic-vector) we can call through to
the underlying type's assignment operator.

Reviewed By: @jdelong

Differential Revision: D2148093
parent 9f41a73a
......@@ -100,23 +100,35 @@ bool dynamic::operator==(dynamic const& o) const {
dynamic& dynamic::operator=(dynamic const& o) {
if (&o != this) {
if (type_ == o.type_) {
#define FB_X(T) *getAddress<T>() = *o.getAddress<T>()
FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
} else {
destroy();
#define FB_X(T) new (getAddress<T>()) T(*o.getAddress<T>())
FB_DYNAMIC_APPLY(o.type_, FB_X);
#undef FB_X
type_ = o.type_;
}
}
return *this;
}
dynamic& dynamic::operator=(dynamic&& o) noexcept {
if (&o != this) {
if (type_ == o.type_) {
#define FB_X(T) *getAddress<T>() = std::move(*o.getAddress<T>())
FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
} else {
destroy();
#define FB_X(T) new (getAddress<T>()) T(std::move(*o.getAddress<T>()))
FB_DYNAMIC_APPLY(o.type_, FB_X);
#undef FB_X
type_ = o.type_;
}
}
return *this;
}
......
......@@ -285,6 +285,29 @@ TEST(Dynamic, GetPtr) {
EXPECT_EQ(dynamic(2), *cobject.get_ptr("two"));
}
TEST(Dynamic, Assignment) {
const dynamic ds[] = { { 1, 2, 3 },
dynamic::object("a", true),
24,
26.5,
true,
"hello", };
const dynamic dd[] = { { 5, 6 },
dynamic::object("t", "T")(1, 7),
9000,
3.14159,
false,
"world", };
for (const auto& source : ds) {
for (const auto& dest : dd) {
dynamic tmp(dest);
EXPECT_EQ(tmp, dest);
tmp = source;
EXPECT_EQ(tmp, source);
}
}
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
gflags::ParseCommandLineFlags(&argc, &argv, true);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment