Simplified memory management in class Json.
By making JsonImpl a friend class and providing a private constructor
that it can call to create new Json objects that initialize their impl_
member in the constructor, it becomes possible to store newly created
Json objects directly into dictionaries_ to simplify program flow.
R=rouslan@chromium.org
BUG=
Review URL: https://codereview.appspot.com/113480043
git-svn-id: http://libaddressinput.googlecode.com/svn/trunk@318 38ededc0-08b8-5190-f2ac-b31f878777ad
diff --git a/cpp/src/util/json.cc b/cpp/src/util/json.cc
index 14a9d11..ef3056b 100644
--- a/cpp/src/util/json.cc
+++ b/cpp/src/util/json.cc
@@ -90,17 +90,11 @@
return false;
}
- Json* sub_dictionary = new Json;
- sub_dictionary->impl_.reset(new JsonImpl(&member->value));
- bool inserted =
- dictionaries_.insert(std::make_pair(key, sub_dictionary)).second;
- // Cannot do work inside of assert(), because the compiler can optimize it
- // away.
- assert(inserted);
- // Avoid unused variable warning when assert() is optimized away.
- (void)inserted;
-
- *value = sub_dictionary;
+ std::pair<std::map<std::string, const Json*>::iterator, bool> result =
+ dictionaries_.insert(
+ std::make_pair(key, new Json(new JsonImpl(&member->value))));
+ assert(result.second);
+ *value = result.first->second;
return true;
}
@@ -143,7 +137,7 @@
DISALLOW_COPY_AND_ASSIGN(JsonImpl);
};
-Json::Json() {}
+Json::Json() : impl_() {}
Json::~Json() {}
@@ -173,5 +167,7 @@
return impl_->GetDictionaryValueForKey(key, value);
}
+Json::Json(JsonImpl* impl) : impl_(impl) {}
+
} // namespace addressinput
} // namespace i18n
diff --git a/cpp/src/util/json.h b/cpp/src/util/json.h
index 1d66aeb..42cd331 100644
--- a/cpp/src/util/json.h
+++ b/cpp/src/util/json.h
@@ -58,6 +58,11 @@
private:
class JsonImpl;
+ friend class JsonImpl;
+
+ // Constructor to be called by JsonImpl.
+ explicit Json(JsonImpl* impl);
+
scoped_ptr<JsonImpl> impl_;
DISALLOW_COPY_AND_ASSIGN(Json);