Skip to content

Commit 9be7a46

Browse files
committed
only clear if use_count == 1
1 parent b68e107 commit 9be7a46

2 files changed

Lines changed: 19 additions & 5 deletions

File tree

src/hjson_value.cpp

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ class Value::ValueImpl {
4949
ValueImpl(const std::string&);
5050
ValueImpl(Type);
5151
~ValueImpl();
52+
static void DeepClear(Value &val);
5253
};
5354

5455

@@ -113,8 +114,9 @@ Value::ValueImpl::ValueImpl(Type _type)
113114

114115

115116
// Bottom-up destruction in order to avoid stack overflow due to recursive destructor calls.
116-
static void _deepClear(Value &val) {
117-
if (val.size()) {
117+
void Value::ValueImpl::DeepClear(Value &val) {
118+
// The map/vector will only be destroyed if use_count == 1
119+
if (val.size() && val.prv.use_count() == 1) {
118120
std::vector<std::pair<Value, int> > v;
119121

120122
v.emplace_back(val, 0);
@@ -124,8 +126,10 @@ static void _deepClear(Value &val) {
124126
v.back().first.clear();
125127
v.pop_back();
126128
} else {
129+
Value &n = v.back().first[v.back().second];
127130
v.back().second++;
128-
if (v.back().first[v.back().second - 1].size()) {
131+
// The map/vector will only be destroyed if use_count == 1
132+
if (n.size() && n.prv.use_count() == 1) {
129133
v.emplace_back(v.back().first[v.back().second - 1], 0);
130134
}
131135
}
@@ -142,13 +146,13 @@ Value::ValueImpl::~ValueImpl() {
142146
break;
143147
case Type::Vector:
144148
for (auto e = v->begin(); e != v->end(); ++e) {
145-
_deepClear(*e);
149+
DeepClear(*e);
146150
}
147151
delete v;
148152
break;
149153
case Type::Map:
150154
for (auto e = m->m.begin(); e != m->m.end(); ++e) {
151-
_deepClear(e->second);
155+
DeepClear(e->second);
152156
}
153157
delete m;
154158
break;

test/test_value.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,16 @@ void test_value() {
2626
delete[] szBrackets;
2727
}
2828

29+
{
30+
Hjson::Value node;
31+
node["a"] = 1;
32+
{
33+
Hjson::Value root;
34+
root["n"] = node;
35+
}
36+
assert(node.size() == 1);
37+
}
38+
2939
{
3040
Hjson::Value valVec(Hjson::Type::Vector);
3141
assert(valVec.type() == Hjson::Type::Vector);

0 commit comments

Comments
 (0)