Ensure we succeed at constructing new sparse and dense arrays.

We could conceivably fail (in the presence of exceptions) to construct
the new dense array after constructing and replacing the sparse array.

Change-Id: Iacc415a2667e4350d8eae57e42a2be81e89dd8e0
Reviewed-on: https://code-review.googlesource.com/c/37392
Reviewed-by: Paul Wankadia <junyer@google.com>
diff --git a/util/sparse_array.h b/util/sparse_array.h
index 86d4d50..2b2d185 100644
--- a/util/sparse_array.h
+++ b/util/sparse_array.h
@@ -431,12 +431,13 @@
     if (sparse_) {
       std::copy_n(sparse_.get(), max_size_, a.get());
     }
-    sparse_ = std::move(a);
 
     std::unique_ptr<IndexValue[]> b(new IndexValue[max_size]);
     if (dense_) {
       std::copy_n(dense_.get(), max_size_, b.get());
     }
+
+    sparse_ = std::move(a);
     dense_ = std::move(b);
 
     MaybeInitializeMemory(max_size_, max_size);
diff --git a/util/sparse_set.h b/util/sparse_set.h
index 3cece2e..18f616a 100644
--- a/util/sparse_set.h
+++ b/util/sparse_set.h
@@ -193,8 +193,9 @@
 template<typename Value>
 void SparseSetT<Value>::resize(int max_size) {
   DebugCheckInvariants();
-  const int old_max_size = dense_.size();
-  if (max_size > old_max_size) {
+  if (max_size > dense_.size()) {
+    const int old_max_size = dense_.size();
+
     PODArray<int> a(max_size);
     if (sparse_.data() != NULL) {
       std::copy_n(sparse_.data(), old_max_size, a.data());