Make CPDF_{Array,Dictionary} methods returning pointers internal-only.

-- Make some methods return retained references.
-- Make other methods return void to prevent misuse.
-- Use `auto` when type already appears on the same line.

Change-Id: Ie02b2324cd111684350c8b59f863323031536f95
Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/98271
Commit-Queue: Tom Sepez <tsepez@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
diff --git a/core/fpdfapi/page/cpdf_docpagedata.cpp b/core/fpdfapi/page/cpdf_docpagedata.cpp
index 7ff7952..4f6cd83 100644
--- a/core/fpdfapi/page/cpdf_docpagedata.cpp
+++ b/core/fpdfapi/page/cpdf_docpagedata.cpp
@@ -57,7 +57,7 @@
     pWidthArray->AppendNew<CPDF_Number>(widths[0]);
     return;
   }
-  CPDF_Array* pWidthArray1 = pWidthArray->AppendNew<CPDF_Array>();
+  auto pWidthArray1 = pWidthArray->AppendNew<CPDF_Array>();
   for (int w : widths)
     pWidthArray1->AppendNew<CPDF_Number>(w);
 }
@@ -655,7 +655,7 @@
   pEncodingDict->SetNewFor<CPDF_Name>("BaseEncoding",
                                       pdfium::font_encodings::kWinAnsiEncoding);
 
-  CPDF_Array* pArray = pEncodingDict->SetNewFor<CPDF_Array>("Differences");
+  auto pArray = pEncodingDict->SetNewFor<CPDF_Array>("Differences");
   pArray->AppendNew<CPDF_Number>(128);
 
   const uint16_t* pUnicodes = kFX_CharsetUnicodes[i].m_pUnicodes;
@@ -678,43 +678,43 @@
   ByteString cmap;
   ByteString ordering;
   int supplement = 0;
-  CPDF_Array* pWidthArray = pFontDict->SetNewFor<CPDF_Array>("W");
+  auto pWidthArray = pFontDict->SetNewFor<CPDF_Array>("W");
   switch (charset) {
     case FX_Charset::kChineseTraditional:
       cmap = "ETenms-B5-H";
       ordering = "CNS1";
       supplement = 4;
       pWidthArray->AppendNew<CPDF_Number>(1);
-      Insert(0x20, 0x7e, pWidthArray);
+      Insert(0x20, 0x7e, pWidthArray.Get());
       break;
     case FX_Charset::kChineseSimplified:
       cmap = "GBK-EUC-H";
       ordering = "GB1";
       supplement = 2;
       pWidthArray->AppendNew<CPDF_Number>(7716);
-      Insert(0x20, 0x20, pWidthArray);
+      Insert(0x20, 0x20, pWidthArray.Get());
       pWidthArray->AppendNew<CPDF_Number>(814);
-      Insert(0x21, 0x7e, pWidthArray);
+      Insert(0x21, 0x7e, pWidthArray.Get());
       break;
     case FX_Charset::kHangul:
       cmap = "KSCms-UHC-H";
       ordering = "Korea1";
       supplement = 2;
       pWidthArray->AppendNew<CPDF_Number>(1);
-      Insert(0x20, 0x7e, pWidthArray);
+      Insert(0x20, 0x7e, pWidthArray.Get());
       break;
     case FX_Charset::kShiftJIS:
       cmap = "90ms-RKSJ-H";
       ordering = "Japan1";
       supplement = 5;
       pWidthArray->AppendNew<CPDF_Number>(231);
-      Insert(0x20, 0x7d, pWidthArray);
+      Insert(0x20, 0x7d, pWidthArray.Get());
       pWidthArray->AppendNew<CPDF_Number>(326);
-      Insert(0xa0, 0xa0, pWidthArray);
+      Insert(0xa0, 0xa0, pWidthArray.Get());
       pWidthArray->AppendNew<CPDF_Number>(327);
-      Insert(0xa1, 0xdf, pWidthArray);
+      Insert(0xa1, 0xdf, pWidthArray.Get());
       pWidthArray->AppendNew<CPDF_Number>(631);
-      Insert(0x7e, 0x7e, pWidthArray);
+      Insert(0x7e, 0x7e, pWidthArray.Get());
       break;
     default:
       break;
@@ -726,13 +726,12 @@
   pFontDict->SetNewFor<CPDF_Name>("Subtype", "CIDFontType2");
   pFontDict->SetNewFor<CPDF_Name>("BaseFont", basefont);
 
-  CPDF_Dictionary* pCIDSysInfo =
-      pFontDict->SetNewFor<CPDF_Dictionary>("CIDSystemInfo");
+  auto pCIDSysInfo = pFontDict->SetNewFor<CPDF_Dictionary>("CIDSystemInfo");
   pCIDSysInfo->SetNewFor<CPDF_String>("Registry", "Adobe", false);
   pCIDSysInfo->SetNewFor<CPDF_String>("Ordering", ordering, false);
   pCIDSysInfo->SetNewFor<CPDF_Number>("Supplement", supplement);
 
-  CPDF_Array* pArray = pBaseDict->SetNewFor<CPDF_Array>("DescendantFonts");
+  auto pArray = pBaseDict->SetNewFor<CPDF_Array>("DescendantFonts");
   pArray->AppendNew<CPDF_Reference>(GetDocument(), pFontDict->GetObjNum());
   return pFontDict.Get();
 }
diff --git a/core/fpdfapi/page/cpdf_function_unittest.cpp b/core/fpdfapi/page/cpdf_function_unittest.cpp
index feacd21..26acf01 100644
--- a/core/fpdfapi/page/cpdf_function_unittest.cpp
+++ b/core/fpdfapi/page/cpdf_function_unittest.cpp
@@ -36,7 +36,7 @@
   auto pDict = pdfium::MakeRetain<CPDF_Dictionary>();
   pDict->SetNewFor<CPDF_Number>("FunctionType", 0);
 
-  CPDF_Array* pArray = pDict->SetNewFor<CPDF_Array>("Domain");
+  auto pArray = pDict->SetNewFor<CPDF_Array>("Domain");
   pArray->AppendNew<CPDF_Number>(0);
   pArray->AppendNew<CPDF_Number>(10);
   EXPECT_FALSE(CPDF_Function::Load(pDict.Get()));
diff --git a/core/fpdfapi/page/cpdf_image.cpp b/core/fpdfapi/page/cpdf_image.cpp
index 056c346..c5f48d6 100644
--- a/core/fpdfapi/page/cpdf_image.cpp
+++ b/core/fpdfapi/page/cpdf_image.cpp
@@ -107,7 +107,7 @@
     csname = "DeviceRGB";
   } else if (info.num_components == 4) {
     csname = "DeviceCMYK";
-    CPDF_Array* pDecode = pDict->SetNewFor<CPDF_Array>("Decode");
+    auto pDecode = pDict->SetNewFor<CPDF_Array>("Decode");
     for (int n = 0; n < 4; n++) {
       pDecode->AppendNew<CPDF_Number>(1);
       pDecode->AppendNew<CPDF_Number>(0);
@@ -117,7 +117,7 @@
   pDict->SetNewFor<CPDF_Number>("BitsPerComponent", info.bits_per_components);
   pDict->SetNewFor<CPDF_Name>("Filter", "DCTDecode");
   if (!info.color_transform) {
-    CPDF_Dictionary* pParms =
+    auto pParms =
         pDict->SetNewFor<CPDF_Dictionary>(pdfium::stream::kDecodeParms);
     pParms->SetNewFor<CPDF_Number>("ColorTransform", 0);
   }
@@ -197,12 +197,12 @@
     if (set_a == 0 || reset_a == 0) {
       pDict->SetNewFor<CPDF_Boolean>("ImageMask", true);
       if (reset_a == 0) {
-        CPDF_Array* pArray = pDict->SetNewFor<CPDF_Array>("Decode");
+        auto pArray = pDict->SetNewFor<CPDF_Array>("Decode");
         pArray->AppendNew<CPDF_Number>(1);
         pArray->AppendNew<CPDF_Number>(0);
       }
     } else {
-      CPDF_Array* pCS = pDict->SetNewFor<CPDF_Array>("ColorSpace");
+      auto pCS = pDict->SetNewFor<CPDF_Array>("ColorSpace");
       pCS->AppendNew<CPDF_Name>("Indexed");
       pCS->AppendNew<CPDF_Name>("DeviceRGB");
       pCS->AppendNew<CPDF_Number>(1);
diff --git a/core/fpdfapi/parser/cpdf_array.cpp b/core/fpdfapi/parser/cpdf_array.cpp
index 4225329..244e884 100644
--- a/core/fpdfapi/parser/cpdf_array.cpp
+++ b/core/fpdfapi/parser/cpdf_array.cpp
@@ -214,7 +214,20 @@
   m_Objects[index] = pNew->MakeReference(pHolder);
 }
 
-CPDF_Object* CPDF_Array::SetAt(size_t index, RetainPtr<CPDF_Object> pObj) {
+void CPDF_Array::SetAt(size_t index, RetainPtr<CPDF_Object> pObj) {
+  (void)SetAtInternal(index, std::move(pObj));
+}
+
+void CPDF_Array::InsertAt(size_t index, RetainPtr<CPDF_Object> pObj) {
+  (void)InsertAtInternal(index, std::move(pObj));
+}
+
+void CPDF_Array::Append(RetainPtr<CPDF_Object> pObj) {
+  (void)AppendInternal(std::move(pObj));
+}
+
+CPDF_Object* CPDF_Array::SetAtInternal(size_t index,
+                                       RetainPtr<CPDF_Object> pObj) {
   CHECK(!IsLocked());
   CHECK(pObj);
   CHECK(pObj->IsInline());
@@ -226,7 +239,8 @@
   return pRet;
 }
 
-CPDF_Object* CPDF_Array::InsertAt(size_t index, RetainPtr<CPDF_Object> pObj) {
+CPDF_Object* CPDF_Array::InsertAtInternal(size_t index,
+                                          RetainPtr<CPDF_Object> pObj) {
   CHECK(!IsLocked());
   CHECK(pObj);
   CHECK(pObj->IsInline());
@@ -238,7 +252,7 @@
   return pRet;
 }
 
-CPDF_Object* CPDF_Array::Append(RetainPtr<CPDF_Object> pObj) {
+CPDF_Object* CPDF_Array::AppendInternal(RetainPtr<CPDF_Object> pObj) {
   CHECK(!IsLocked());
   CHECK(pObj);
   CHECK(pObj->IsInline());
diff --git a/core/fpdfapi/parser/cpdf_array.h b/core/fpdfapi/parser/cpdf_array.h
index 71b8c60..bcf04e2 100644
--- a/core/fpdfapi/parser/cpdf_array.h
+++ b/core/fpdfapi/parser/cpdf_array.h
@@ -75,68 +75,61 @@
   absl::optional<size_t> Find(const CPDF_Object* pThat) const;
   bool Contains(const CPDF_Object* pThat) const;
 
-  // Creates object owned by the array, returns unowned pointer to it.
+  // Creates object owned by the array, and returns a retained pointer to it.
   // We have special cases for objects that can intern strings from
   // a ByteStringPool. Prefer using these templates over direct calls
   // to Append()/SetAt()/InsertAt() since by creating a new object with no
   // previous references, they ensure cycles can not be introduced.
   template <typename T, typename... Args>
-  typename std::enable_if<!CanInternStrings<T>::value, T*>::type AppendNew(
-      Args&&... args) {
-    return static_cast<T*>(
-        Append(pdfium::MakeRetain<T>(std::forward<Args>(args)...)));
+  typename std::enable_if<!CanInternStrings<T>::value, RetainPtr<T>>::type
+  AppendNew(Args&&... args) {
+    return pdfium::WrapRetain(static_cast<T*>(
+        AppendInternal(pdfium::MakeRetain<T>(std::forward<Args>(args)...))));
   }
   template <typename T, typename... Args>
-  typename std::enable_if<CanInternStrings<T>::value, T*>::type AppendNew(
-      Args&&... args) {
-    return static_cast<T*>(
-        Append(pdfium::MakeRetain<T>(m_pPool, std::forward<Args>(args)...)));
+  typename std::enable_if<CanInternStrings<T>::value, RetainPtr<T>>::type
+  AppendNew(Args&&... args) {
+    return pdfium::WrapRetain(static_cast<T*>(AppendInternal(
+        pdfium::MakeRetain<T>(m_pPool, std::forward<Args>(args)...))));
   }
   template <typename T, typename... Args>
-  typename std::enable_if<!CanInternStrings<T>::value, T*>::type SetNewAt(
-      size_t index,
-      Args&&... args) {
-    return static_cast<T*>(
-        SetAt(index, pdfium::MakeRetain<T>(std::forward<Args>(args)...)));
+  typename std::enable_if<!CanInternStrings<T>::value, RetainPtr<T>>::type
+  SetNewAt(size_t index, Args&&... args) {
+    return pdfium::WrapRetain(static_cast<T*>(SetAtInternal(
+        index, pdfium::MakeRetain<T>(std::forward<Args>(args)...))));
   }
   template <typename T, typename... Args>
-  typename std::enable_if<CanInternStrings<T>::value, T*>::type SetNewAt(
-      size_t index,
-      Args&&... args) {
-    return static_cast<T*>(SetAt(
-        index, pdfium::MakeRetain<T>(m_pPool, std::forward<Args>(args)...)));
+  typename std::enable_if<CanInternStrings<T>::value, RetainPtr<T>>::type
+  SetNewAt(size_t index, Args&&... args) {
+    return pdfium::WrapRetain(static_cast<T*>(SetAtInternal(
+        index, pdfium::MakeRetain<T>(m_pPool, std::forward<Args>(args)...))));
   }
   template <typename T, typename... Args>
-  typename std::enable_if<!CanInternStrings<T>::value, T*>::type InsertNewAt(
-      size_t index,
-      Args&&... args) {
-    return static_cast<T*>(
-        InsertAt(index, pdfium::MakeRetain<T>(std::forward<Args>(args)...)));
+  typename std::enable_if<!CanInternStrings<T>::value, RetainPtr<T>>::type
+  InsertNewAt(size_t index, Args&&... args) {
+    return pdfium::WrapRetain(static_cast<T*>(InsertAtInternal(
+        index, pdfium::MakeRetain<T>(std::forward<Args>(args)...))));
   }
   template <typename T, typename... Args>
-  typename std::enable_if<CanInternStrings<T>::value, T*>::type InsertNewAt(
-      size_t index,
-      Args&&... args) {
-    return static_cast<T*>(InsertAt(
-        index, pdfium::MakeRetain<T>(m_pPool, std::forward<Args>(args)...)));
+  typename std::enable_if<CanInternStrings<T>::value, RetainPtr<T>>::type
+  InsertNewAt(size_t index, Args&&... args) {
+    return pdfium::WrapRetain(static_cast<T*>(InsertAtInternal(
+        index, pdfium::MakeRetain<T>(m_pPool, std::forward<Args>(args)...))));
   }
 
   // Adds non-null `pObj` to the end of the array, growing as appropriate.
-  // Retains reference to `pObj`, and returns raw pointer for convenience.
-  CPDF_Object* Append(RetainPtr<CPDF_Object> pObj);
+  void Append(RetainPtr<CPDF_Object> pObj);
 
-  // Overwrites the object at `index` with non-null `pObj`. If `index` is
-  // less than the array size, then retains reference to `pObj`, and returns
-  // raw pointer for convenience. Otherwise, `index` is out of bounds, and
-  // `pObj` is neither stored nor retained, and nullptr is returned.
-  CPDF_Object* SetAt(size_t index, RetainPtr<CPDF_Object> pObj);
+  // Overwrites the object at `index` with non-null `pObj`, if it is
+  // in bounds. Otherwise, `index` is out of bounds, and `pObj` is
+  // not stored.
+  void SetAt(size_t index, RetainPtr<CPDF_Object> pObj);
 
   // Inserts non-null `pObj` at `index` and shifts by one position all of the
-  // objects beyond it like std::vector::insert(). If `index` is less than or
-  // equal to the current array size, then retains reference to `pObj`, and
-  // returns raw pointer for convenience. Otherwise, `index` is out of bounds,
-  // and `pObj` is neither stored nor retained, and nullptr is returned.
-  CPDF_Object* InsertAt(size_t index, RetainPtr<CPDF_Object> pObj);
+  // objects beyond it like std::vector::insert(), if `index` is less than or
+  // equal to the current array size. Otherwise, `index` is out of bounds,
+  // and `pObj` is not stored.
+  void InsertAt(size_t index, RetainPtr<CPDF_Object> pObj);
 
   void Clear();
   void RemoveAt(size_t index);
@@ -154,6 +147,9 @@
   // No guarantees about result lifetime, use with caution.
   const CPDF_Object* GetObjectAtInternal(size_t index) const;
   CPDF_Object* GetMutableObjectAtInternal(size_t index);
+  CPDF_Object* AppendInternal(RetainPtr<CPDF_Object> pObj);
+  CPDF_Object* SetAtInternal(size_t index, RetainPtr<CPDF_Object> pObj);
+  CPDF_Object* InsertAtInternal(size_t index, RetainPtr<CPDF_Object> pObj);
 
   RetainPtr<CPDF_Object> CloneNonCyclic(
       bool bDirect,
diff --git a/core/fpdfapi/parser/cpdf_dictionary.cpp b/core/fpdfapi/parser/cpdf_dictionary.cpp
index cba8091..84f0d79 100644
--- a/core/fpdfapi/parser/cpdf_dictionary.cpp
+++ b/core/fpdfapi/parser/cpdf_dictionary.cpp
@@ -182,7 +182,7 @@
   RetainPtr<CPDF_Dictionary> result = GetMutableDictFor(key);
   if (result)
     return result;
-  return pdfium::WrapRetain(SetNewFor<CPDF_Dictionary>(key));
+  return SetNewFor<CPDF_Dictionary>(key);
 }
 
 const CPDF_Array* CPDF_Dictionary::GetArrayForInternal(
@@ -205,7 +205,7 @@
   RetainPtr<CPDF_Array> result = GetMutableArrayFor(key);
   if (result)
     return result;
-  return pdfium::WrapRetain(SetNewFor<CPDF_Array>(key));
+  return SetNewFor<CPDF_Array>(key);
 }
 
 const CPDF_Stream* CPDF_Dictionary::GetStreamForInternal(
@@ -270,8 +270,13 @@
   return result;
 }
 
-CPDF_Object* CPDF_Dictionary::SetFor(const ByteString& key,
-                                     RetainPtr<CPDF_Object> pObj) {
+void CPDF_Dictionary::SetFor(const ByteString& key,
+                             RetainPtr<CPDF_Object> pObj) {
+  (void)SetForInternal(key, std::move(pObj));
+}
+
+CPDF_Object* CPDF_Dictionary::SetForInternal(const ByteString& key,
+                                             RetainPtr<CPDF_Object> pObj) {
   CHECK(!IsLocked());
   if (!pObj) {
     m_Map.erase(key);
@@ -323,7 +328,7 @@
 
 void CPDF_Dictionary::SetRectFor(const ByteString& key,
                                  const CFX_FloatRect& rect) {
-  CPDF_Array* pArray = SetNewFor<CPDF_Array>(key);
+  auto pArray = SetNewFor<CPDF_Array>(key);
   pArray->AppendNew<CPDF_Number>(rect.left);
   pArray->AppendNew<CPDF_Number>(rect.bottom);
   pArray->AppendNew<CPDF_Number>(rect.right);
@@ -332,7 +337,7 @@
 
 void CPDF_Dictionary::SetMatrixFor(const ByteString& key,
                                    const CFX_Matrix& matrix) {
-  CPDF_Array* pArray = SetNewFor<CPDF_Array>(key);
+  auto pArray = SetNewFor<CPDF_Array>(key);
   pArray->AppendNew<CPDF_Number>(matrix.a);
   pArray->AppendNew<CPDF_Number>(matrix.b);
   pArray->AppendNew<CPDF_Number>(matrix.c);
diff --git a/core/fpdfapi/parser/cpdf_dictionary.h b/core/fpdfapi/parser/cpdf_dictionary.h
index b6f6b02..b7b6c1d 100644
--- a/core/fpdfapi/parser/cpdf_dictionary.h
+++ b/core/fpdfapi/parser/cpdf_dictionary.h
@@ -88,24 +88,22 @@
   // a new object with no previous references, they ensure cycles can not be
   // introduced.
   template <typename T, typename... Args>
-  typename std::enable_if<!CanInternStrings<T>::value, T*>::type SetNewFor(
-      const ByteString& key,
-      Args&&... args) {
-    return static_cast<T*>(
-        SetFor(key, pdfium::MakeRetain<T>(std::forward<Args>(args)...)));
+  typename std::enable_if<!CanInternStrings<T>::value, RetainPtr<T>>::type
+  SetNewFor(const ByteString& key, Args&&... args) {
+    return pdfium::WrapRetain(static_cast<T*>(SetForInternal(
+        key, pdfium::MakeRetain<T>(std::forward<Args>(args)...))));
   }
   template <typename T, typename... Args>
-  typename std::enable_if<CanInternStrings<T>::value, T*>::type SetNewFor(
-      const ByteString& key,
-      Args&&... args) {
-    return static_cast<T*>(SetFor(
-        key, pdfium::MakeRetain<T>(m_pPool, std::forward<Args>(args)...)));
+  typename std::enable_if<CanInternStrings<T>::value, RetainPtr<T>>::type
+  SetNewFor(const ByteString& key, Args&&... args) {
+    return pdfium::WrapRetain(static_cast<T*>(SetForInternal(
+        key, pdfium::MakeRetain<T>(m_pPool, std::forward<Args>(args)...))));
   }
 
   // If |pObj| is null, then |key| is erased from the map. Otherwise, takes
-  // ownership of |pObj|, returns an unowned pointer to it. Invalidates
-  // iterators for the element with the key |key|.
-  CPDF_Object* SetFor(const ByteString& key, RetainPtr<CPDF_Object> pObj);
+  // ownership of |pObj| and stores in in the map. Invalidates iterators for
+  // the element with the key |key|.
+  void SetFor(const ByteString& key, RetainPtr<CPDF_Object> pObj);
 
   // Convenience functions to convert native objects to array form.
   void SetRectFor(const ByteString& key, const CFX_FloatRect& rect);
@@ -137,6 +135,8 @@
   const CPDF_Number* GetNumberForInternal(const ByteString& key) const;
   const CPDF_Stream* GetStreamForInternal(const ByteString& key) const;
   const CPDF_String* GetStringForInternal(const ByteString& key) const;
+  CPDF_Object* SetForInternal(const ByteString& key,
+                              RetainPtr<CPDF_Object> pObj);
 
   ByteString MaybeIntern(const ByteString& str);
   RetainPtr<CPDF_Object> CloneNonCyclic(
diff --git a/core/fpdfapi/parser/cpdf_document_unittest.cpp b/core/fpdfapi/parser/cpdf_document_unittest.cpp
index ee9756c..27050fe 100644
--- a/core/fpdfapi/parser/cpdf_document_unittest.cpp
+++ b/core/fpdfapi/parser/cpdf_document_unittest.cpp
@@ -112,7 +112,8 @@
     allPages->AppendNew<CPDF_Reference>(
         this, AddIndirectObject(CreateNumberedPage(1))->GetObjNum());
     // Page without pageNum.
-    inlined_page_ = allPages->Append(CreateNumberedPage(2));
+    inlined_page_ = CreateNumberedPage(2);
+    allPages->Append(inlined_page_);
     CPDF_Dictionary* pagesDict =
         CreatePageTreeNode(std::move(allPages), this, 3);
     SetRootForTesting(NewIndirect<CPDF_Dictionary>().Get());
@@ -121,10 +122,10 @@
     ResizePageListForTesting(3);
   }
 
-  const CPDF_Object* inlined_page() const { return inlined_page_; }
+  const CPDF_Object* inlined_page() const { return inlined_page_.Get(); }
 
  private:
-  const CPDF_Object* inlined_page_;
+  RetainPtr<CPDF_Object> inlined_page_;
 };
 
 class TestLinearized final : public CPDF_LinearizedHeader {
diff --git a/core/fpdfapi/parser/cpdf_object_avail_unittest.cpp b/core/fpdfapi/parser/cpdf_object_avail_unittest.cpp
index a71a1db..89a089e 100644
--- a/core/fpdfapi/parser/cpdf_object_avail_unittest.cpp
+++ b/core/fpdfapi/parser/cpdf_object_avail_unittest.cpp
@@ -321,7 +321,7 @@
 
   holder.GetTestObject(1)->GetMutableDict()->SetNewFor<CPDF_Reference>(
       "Data", &holder, 2);
-  auto* root =
+  auto root =
       holder.GetTestObject(1)->GetMutableDict()->SetNewFor<CPDF_Dictionary>(
           "Dict");
 
@@ -330,11 +330,9 @@
   holder.AddObject(2, pdfium::MakeRetain<CPDF_String>(nullptr, "Data", false),
                    TestHolder::ObjectState::Unavailable);
 
-  CPDF_ObjectAvail avail(holder.GetValidator(), &holder, root);
-
+  CPDF_ObjectAvail avail(holder.GetValidator(), &holder, root.Get());
   EXPECT_EQ(CPDF_DataAvail::kDataNotAvailable, avail.CheckAvail());
 
   holder.SetObjectState(2, TestHolder::ObjectState::Available);
-
   EXPECT_EQ(CPDF_DataAvail::kDataAvailable, avail.CheckAvail());
 }
diff --git a/core/fpdfapi/parser/cpdf_object_unittest.cpp b/core/fpdfapi/parser/cpdf_object_unittest.cpp
index 54c2a03..1c0b1d1 100644
--- a/core/fpdfapi/parser/cpdf_object_unittest.cpp
+++ b/core/fpdfapi/parser/cpdf_object_unittest.cpp
@@ -593,7 +593,7 @@
   }
   {
     // Array of array.
-    CPDF_Array* vals[3];
+    RetainPtr<CPDF_Array> vals[3];
     auto arr = pdfium::MakeRetain<CPDF_Array>();
     for (size_t i = 0; i < 3; ++i) {
       vals[i] = arr->AppendNew<CPDF_Array>();
@@ -603,19 +603,19 @@
       }
     }
     for (size_t i = 0; i < 3; ++i) {
-      TestArrayAccessors(arr.Get(), i,  // Array and index.
-                         "",            // String value.
-                         nullptr,       // Const string value.
-                         0,             // Integer value.
-                         0,             // Float value.
-                         vals[i],       // Array value.
-                         nullptr,       // Dictionary value.
-                         nullptr);      // Stream value.
+      TestArrayAccessors(arr.Get(), i,   // Array and index.
+                         "",             // String value.
+                         nullptr,        // Const string value.
+                         0,              // Integer value.
+                         0,              // Float value.
+                         vals[i].Get(),  // Array value.
+                         nullptr,        // Dictionary value.
+                         nullptr);       // Stream value.
     }
   }
   {
     // Dictionary array.
-    CPDF_Dictionary* vals[3];
+    RetainPtr<CPDF_Dictionary> vals[3];
     auto arr = pdfium::MakeRetain<CPDF_Array>();
     for (size_t i = 0; i < 3; ++i) {
       vals[i] = arr->AppendNew<CPDF_Dictionary>();
@@ -628,20 +628,20 @@
       }
     }
     for (size_t i = 0; i < 3; ++i) {
-      TestArrayAccessors(arr.Get(), i,  // Array and index.
-                         "",            // String value.
-                         nullptr,       // Const string value.
-                         0,             // Integer value.
-                         0,             // Float value.
-                         nullptr,       // Array value.
-                         vals[i],       // Dictionary value.
-                         nullptr);      // Stream value.
+      TestArrayAccessors(arr.Get(), i,   // Array and index.
+                         "",             // String value.
+                         nullptr,        // Const string value.
+                         0,              // Integer value.
+                         0,              // Float value.
+                         nullptr,        // Array value.
+                         vals[i].Get(),  // Dictionary value.
+                         nullptr);       // Stream value.
     }
   }
   {
     // Stream array.
     RetainPtr<CPDF_Dictionary> vals[3];
-    CPDF_Stream* stream_vals[3];
+    RetainPtr<CPDF_Stream> stream_vals[3];
     auto arr = pdfium::MakeRetain<CPDF_Array>();
     for (size_t i = 0; i < 3; ++i) {
       vals[i] = pdfium::MakeRetain<CPDF_Dictionary>();
@@ -661,14 +661,14 @@
           arr->AppendNew<CPDF_Stream>(std::move(data), data_size, vals[i]);
     }
     for (size_t i = 0; i < 3; ++i) {
-      TestArrayAccessors(arr.Get(), i,     // Array and index.
-                         "",               // String value.
-                         nullptr,          // Const string value.
-                         0,                // Integer value.
-                         0,                // Float value.
-                         nullptr,          // Array value.
-                         vals[i].Get(),    // Dictionary value.
-                         stream_vals[i]);  // Stream value.
+      TestArrayAccessors(arr.Get(), i,           // Array and index.
+                         "",                     // String value.
+                         nullptr,                // Const string value.
+                         0,                      // Integer value.
+                         0,                      // Float value.
+                         nullptr,                // Array value.
+                         vals[i].Get(),          // Dictionary value.
+                         stream_vals[i].Get());  // Stream value.
     }
   }
   {
@@ -686,11 +686,11 @@
     arr->InsertNewAt<CPDF_Name>(9, "test");
     arr->InsertNewAt<CPDF_Null>(10);
 
-    CPDF_Array* arr_val = arr->InsertNewAt<CPDF_Array>(11);
+    auto arr_val = arr->InsertNewAt<CPDF_Array>(11);
     arr_val->AppendNew<CPDF_Number>(1);
     arr_val->AppendNew<CPDF_Number>(2);
 
-    CPDF_Dictionary* dict_val = arr->InsertNewAt<CPDF_Dictionary>(12);
+    auto dict_val = arr->InsertNewAt<CPDF_Dictionary>(12);
     dict_val->SetNewFor<CPDF_String>("key1", "Linda", false);
     dict_val->SetNewFor<CPDF_String>("key2", "Zoe", false);
 
@@ -704,8 +704,8 @@
     std::unique_ptr<uint8_t, FxFreeDeleter> buf(
         FX_AllocUninit(uint8_t, buf_size));
     memcpy(buf.get(), data, buf_size);
-    CPDF_Stream* stream_val = arr->InsertNewAt<CPDF_Stream>(
-        13, std::move(buf), buf_size, stream_dict);
+    auto stream_val = arr->InsertNewAt<CPDF_Stream>(13, std::move(buf),
+                                                    buf_size, stream_dict);
     const char* const expected_str[] = {
         "true",          "false", "0",    "-1234", "2345", "0.05", "",
         "It is a test!", "NAME",  "test", "",      "",     "",     ""};
@@ -835,7 +835,7 @@
 TEST(PDFArrayTest, ConvertIndirect) {
   CPDF_IndirectObjectHolder objects_holder;
   auto array = pdfium::MakeRetain<CPDF_Array>();
-  CPDF_Object* pObj = array->AppendNew<CPDF_Number>(42);
+  auto pObj = array->AppendNew<CPDF_Number>(42);
   array->ConvertToIndirectObjectAt(0, &objects_holder);
   RetainPtr<const CPDF_Object> pRef = array->GetObjectAt(0);
   RetainPtr<const CPDF_Object> pNum = array->GetDirectObjectAt(0);
@@ -943,7 +943,7 @@
   {
     // Create a dictionary/array pair with a reference loop.
     auto arr_obj = pdfium::MakeRetain<CPDF_Array>();
-    CPDF_Dictionary* dict_obj = arr_obj->InsertNewAt<CPDF_Dictionary>(0);
+    auto dict_obj = arr_obj->InsertNewAt<CPDF_Dictionary>(0);
     dict_obj->SetFor("arr", arr_obj);
     // Clone this object to see whether stack overflow will be triggered.
     RetainPtr<CPDF_Array> cloned_array = ToArray(arr_obj->Clone());
@@ -960,7 +960,7 @@
   {
     // Create a dictionary/stream pair with a reference loop.
     auto dict_obj = pdfium::MakeRetain<CPDF_Dictionary>();
-    CPDF_Stream* stream_obj =
+    auto stream_obj =
         dict_obj->SetNewFor<CPDF_Stream>("stream", nullptr, 0, dict_obj);
     // Clone this object to see whether stack overflow will be triggered.
     RetainPtr<CPDF_Stream> cloned_stream = ToStream(stream_obj->Clone());
@@ -1006,7 +1006,7 @@
 TEST(PDFDictionaryTest, ConvertIndirect) {
   CPDF_IndirectObjectHolder objects_holder;
   auto dict = pdfium::MakeRetain<CPDF_Dictionary>();
-  CPDF_Object* pObj = dict->SetNewFor<CPDF_Number>("clams", 42);
+  auto pObj = dict->SetNewFor<CPDF_Number>("clams", 42);
   dict->ConvertToIndirectObjectFor("clams", &objects_holder);
   RetainPtr<const CPDF_Object> pRef = dict->GetObjectFor("clams");
   RetainPtr<const CPDF_Object> pNum = dict->GetDirectObjectFor("clams");
@@ -1019,7 +1019,7 @@
 
 TEST(PDFDictionaryTest, ExtractObjectOnRemove) {
   auto dict = pdfium::MakeRetain<CPDF_Dictionary>();
-  CPDF_Object* pObj = dict->SetNewFor<CPDF_Number>("child", 42);
+  auto pObj = dict->SetNewFor<CPDF_Number>("child", 42);
   auto extracted_object = dict->RemoveFor("child");
   EXPECT_EQ(pObj, extracted_object.Get());
 
diff --git a/core/fpdfapi/parser/fpdf_parser_decode_unittest.cpp b/core/fpdfapi/parser/fpdf_parser_decode_unittest.cpp
index fd5787b..39c82c6 100644
--- a/core/fpdfapi/parser/fpdf_parser_decode_unittest.cpp
+++ b/core/fpdfapi/parser/fpdf_parser_decode_unittest.cpp
@@ -151,7 +151,7 @@
   {
     // Valid 1 element filter array.
     auto dict = pdfium::MakeRetain<CPDF_Dictionary>();
-    auto* filter_array = dict->SetNewFor<CPDF_Array>("Filter");
+    auto filter_array = dict->SetNewFor<CPDF_Array>("Filter");
     filter_array->AppendNew<CPDF_Name>("FooBar");
     absl::optional<DecoderArray> decoder_array = GetDecoderArray(dict);
     ASSERT_TRUE(decoder_array.has_value());
@@ -161,7 +161,7 @@
   {
     // Valid 2 element filter array.
     auto dict = pdfium::MakeRetain<CPDF_Dictionary>();
-    auto* filter_array = dict->SetNewFor<CPDF_Array>("Filter");
+    auto filter_array = dict->SetNewFor<CPDF_Array>("Filter");
     filter_array->AppendNew<CPDF_Name>("AHx");
     filter_array->AppendNew<CPDF_Name>("LZWDecode");
     absl::optional<DecoderArray> decoder_array = GetDecoderArray(dict);
@@ -173,7 +173,7 @@
   {
     // Invalid 2 element filter array.
     auto dict = pdfium::MakeRetain<CPDF_Dictionary>();
-    auto* invalid_filter_array = dict->SetNewFor<CPDF_Array>("Filter");
+    auto invalid_filter_array = dict->SetNewFor<CPDF_Array>("Filter");
     invalid_filter_array->AppendNew<CPDF_Name>("DCTDecode");
     invalid_filter_array->AppendNew<CPDF_Name>("CCITTFaxDecode");
     absl::optional<DecoderArray> decoder_array = GetDecoderArray(dict);
diff --git a/core/fpdfapi/parser/fpdf_parser_utility_unittest.cpp b/core/fpdfapi/parser/fpdf_parser_utility_unittest.cpp
index a895587..6260203 100644
--- a/core/fpdfapi/parser/fpdf_parser_utility_unittest.cpp
+++ b/core/fpdfapi/parser/fpdf_parser_utility_unittest.cpp
@@ -68,7 +68,7 @@
     EXPECT_FALSE(ValidateDictAllResourcesOfType(nullptr, "bar"));
 
     // Add two correct dictionary entries and one string entry.
-    CPDF_Dictionary* new_dict = dict->SetNewFor<CPDF_Dictionary>("f1");
+    auto new_dict = dict->SetNewFor<CPDF_Dictionary>("f1");
     new_dict->SetNewFor<CPDF_Name>("Type", "foo");
     new_dict = dict->SetNewFor<CPDF_Dictionary>("f2");
     new_dict->SetNewFor<CPDF_Name>("Type", "foo");
diff --git a/core/fpdfapi/render/cpdf_docrenderdata_unittest.cpp b/core/fpdfapi/render/cpdf_docrenderdata_unittest.cpp
index 49c1148..abf7d22 100644
--- a/core/fpdfapi/render/cpdf_docrenderdata_unittest.cpp
+++ b/core/fpdfapi/render/cpdf_docrenderdata_unittest.cpp
@@ -73,20 +73,19 @@
 RetainPtr<CPDF_Stream> CreateType0FunctionStream() {
   auto func_dict = pdfium::MakeRetain<CPDF_Dictionary>();
   func_dict->SetNewFor<CPDF_Number>("FunctionType", 0);
+  func_dict->SetNewFor<CPDF_Number>("BitsPerSample", 8);
 
-  CPDF_Array* domain_array = func_dict->SetNewFor<CPDF_Array>("Domain");
+  auto domain_array = func_dict->SetNewFor<CPDF_Array>("Domain");
   domain_array->AppendNew<CPDF_Number>(0);
   domain_array->AppendNew<CPDF_Number>(1);
 
-  CPDF_Array* range_array = func_dict->SetNewFor<CPDF_Array>("Range");
+  auto range_array = func_dict->SetNewFor<CPDF_Array>("Range");
   range_array->AppendNew<CPDF_Number>(0);
   range_array->AppendNew<CPDF_Number>(0.5f);
 
-  CPDF_Array* size_array = func_dict->SetNewFor<CPDF_Array>("Size");
+  auto size_array = func_dict->SetNewFor<CPDF_Array>("Size");
   size_array->AppendNew<CPDF_Number>(4);
 
-  func_dict->SetNewFor<CPDF_Number>("BitsPerSample", 8);
-
   static const char content[] = "1234";
   size_t len = std::size(content);
   std::unique_ptr<uint8_t, FxFreeDeleter> buf(FX_AllocUninit(uint8_t, len));
@@ -100,16 +99,16 @@
   func_dict->SetNewFor<CPDF_Number>("FunctionType", 2);
   func_dict->SetNewFor<CPDF_Number>("N", 1);
 
-  CPDF_Array* domain_array = func_dict->SetNewFor<CPDF_Array>("Domain");
+  auto domain_array = func_dict->SetNewFor<CPDF_Array>("Domain");
   domain_array->AppendNew<CPDF_Number>(0);
   domain_array->AppendNew<CPDF_Number>(1);
 
-  CPDF_Array* c0_array = func_dict->SetNewFor<CPDF_Array>("C0");
+  auto c0_array = func_dict->SetNewFor<CPDF_Array>("C0");
   c0_array->AppendNew<CPDF_Number>(0.1f);
   c0_array->AppendNew<CPDF_Number>(0.2f);
   c0_array->AppendNew<CPDF_Number>(0.8f);
 
-  CPDF_Array* c1_array = func_dict->SetNewFor<CPDF_Array>("C1");
+  auto c1_array = func_dict->SetNewFor<CPDF_Array>("C1");
   c1_array->AppendNew<CPDF_Number>(0.05f);
   c1_array->AppendNew<CPDF_Number>(0.01f);
   c1_array->AppendNew<CPDF_Number>(0.4f);
@@ -121,11 +120,11 @@
   auto func_dict = pdfium::MakeRetain<CPDF_Dictionary>();
   func_dict->SetNewFor<CPDF_Number>("FunctionType", 4);
 
-  CPDF_Array* domain_array = func_dict->SetNewFor<CPDF_Array>("Domain");
+  auto domain_array = func_dict->SetNewFor<CPDF_Array>("Domain");
   domain_array->AppendNew<CPDF_Number>(0);
   domain_array->AppendNew<CPDF_Number>(1);
 
-  CPDF_Array* range_array = func_dict->SetNewFor<CPDF_Array>("Range");
+  auto range_array = func_dict->SetNewFor<CPDF_Array>("Range");
   range_array->AppendNew<CPDF_Number>(-1);
   range_array->AppendNew<CPDF_Number>(1);
 
@@ -141,11 +140,11 @@
   auto func_dict = pdfium::MakeRetain<CPDF_Dictionary>();
   func_dict->SetNewFor<CPDF_Number>("FunctionType", 4);
 
-  CPDF_Array* domain_array = func_dict->SetNewFor<CPDF_Array>("Domain");
+  auto domain_array = func_dict->SetNewFor<CPDF_Array>("Domain");
   domain_array->AppendNew<CPDF_Number>(0);
   domain_array->AppendNew<CPDF_Number>(1);
 
-  CPDF_Array* range_array = func_dict->SetNewFor<CPDF_Array>("Range");
+  auto range_array = func_dict->SetNewFor<CPDF_Array>("Range");
   range_array->AppendNew<CPDF_Number>(-1);
   range_array->AppendNew<CPDF_Number>(1);
 
diff --git a/core/fpdfdoc/cpdf_bafontmap_unittest.cpp b/core/fpdfdoc/cpdf_bafontmap_unittest.cpp
index 6ede10b..e702169 100644
--- a/core/fpdfdoc/cpdf_bafontmap_unittest.cpp
+++ b/core/fpdfdoc/cpdf_bafontmap_unittest.cpp
@@ -40,10 +40,10 @@
 TEST_F(BAFontMapTest, Bug853238) {
   CPDF_TestDocument doc;
   auto root_dict = pdfium::MakeRetain<CPDF_Dictionary>();
-  auto* acroform_dict = root_dict->SetNewFor<CPDF_Dictionary>("AcroForm");
-  auto* annot_dr_dict = acroform_dict->SetNewFor<CPDF_Dictionary>("DR");
-  auto* annot_font_dict = annot_dr_dict->SetNewFor<CPDF_Dictionary>("Font");
-  auto* annot_font_f1_dict = annot_font_dict->SetNewFor<CPDF_Dictionary>("F1");
+  auto acroform_dict = root_dict->SetNewFor<CPDF_Dictionary>("AcroForm");
+  auto annot_dr_dict = acroform_dict->SetNewFor<CPDF_Dictionary>("DR");
+  auto annot_font_dict = annot_dr_dict->SetNewFor<CPDF_Dictionary>("Font");
+  auto annot_font_f1_dict = annot_font_dict->SetNewFor<CPDF_Dictionary>("F1");
   annot_font_f1_dict->SetNewFor<CPDF_Name>("Type", "Font");
   annot_font_f1_dict->SetNewFor<CPDF_Name>("Subtype", "Type1");
   annot_font_f1_dict->SetNewFor<CPDF_Name>("BaseFont", "Times-Roman");
diff --git a/core/fpdfdoc/cpdf_formfield.cpp b/core/fpdfdoc/cpdf_formfield.cpp
index 26c9530..2f9ec84 100644
--- a/core/fpdfdoc/cpdf_formfield.cpp
+++ b/core/fpdfdoc/cpdf_formfield.cpp
@@ -516,7 +516,7 @@
   if (GetType() != kListBox) {
     m_pDict->SetNewFor<CPDF_String>(pdfium::form_fields::kV,
                                     opt_value.AsStringView());
-    CPDF_Array* pI = m_pDict->SetNewFor<CPDF_Array>("I");
+    auto pI = m_pDict->SetNewFor<CPDF_Array>("I");
     pI->AppendNew<CPDF_Number>(index);
     return;
   }
@@ -528,7 +528,7 @@
     return;
   }
 
-  CPDF_Array* pArray = m_pDict->SetNewFor<CPDF_Array>(pdfium::form_fields::kV);
+  auto pArray = m_pDict->SetNewFor<CPDF_Array>(pdfium::form_fields::kV);
   for (int i = 0; i < CountOptions(); i++) {
     if (i == index || IsItemSelected(i))
       pArray->AppendNew<CPDF_String>(GetOptionValue(i).AsStringView());
diff --git a/core/fpdfdoc/cpdf_formfield_unittest.cpp b/core/fpdfdoc/cpdf_formfield_unittest.cpp
index 355d3b6..ea51901 100644
--- a/core/fpdfdoc/cpdf_formfield_unittest.cpp
+++ b/core/fpdfdoc/cpdf_formfield_unittest.cpp
@@ -83,7 +83,7 @@
   name = CPDF_FormField::GetFullNameForDict(root.Get());
   EXPECT_STREQ("bar.foo", name.ToUTF8().c_str());
 
-  CPDF_Dictionary* dict2 = dict1->SetNewFor<CPDF_Dictionary>("Parent");
+  auto dict2 = dict1->SetNewFor<CPDF_Dictionary>("Parent");
   name = CPDF_FormField::GetFullNameForDict(root.Get());
   EXPECT_STREQ("bar.foo", name.ToUTF8().c_str());
 
@@ -99,7 +99,7 @@
   EXPECT_STREQ("qux.bar.foo", name.ToUTF8().c_str());
   name = CPDF_FormField::GetFullNameForDict(dict1.Get());
   EXPECT_STREQ("foo.qux.bar", name.ToUTF8().c_str());
-  name = CPDF_FormField::GetFullNameForDict(dict2);
+  name = CPDF_FormField::GetFullNameForDict(dict2.Get());
   EXPECT_STREQ("bar.foo.qux", name.ToUTF8().c_str());
   name = CPDF_FormField::GetFullNameForDict(dict3.Get());
   EXPECT_STREQ("bar.foo.qux", name.ToUTF8().c_str());
diff --git a/core/fpdfdoc/cpdf_generateap.cpp b/core/fpdfdoc/cpdf_generateap.cpp
index 91aea41..063e308 100644
--- a/core/fpdfdoc/cpdf_generateap.cpp
+++ b/core/fpdfdoc/cpdf_generateap.cpp
@@ -1075,8 +1075,7 @@
         if (!ValidateFontResourceDict(pStreamResFontList.Get()))
           return;
       } else {
-        pStreamResFontList.Reset(
-            pStreamResList->SetNewFor<CPDF_Dictionary>("Font"));
+        pStreamResFontList = pStreamResList->SetNewFor<CPDF_Dictionary>("Font");
       }
       if (!pStreamResFontList->KeyExist(font_name)) {
         pStreamResFontList->SetNewFor<CPDF_Reference>(font_name, pDoc,
@@ -1329,8 +1328,7 @@
     if (!ValidateFontResourceDict(pStreamResFontList.Get()))
       return;
   } else {
-    pStreamResFontList.Reset(
-        pStreamResList->SetNewFor<CPDF_Dictionary>("Font"));
+    pStreamResFontList = pStreamResList->SetNewFor<CPDF_Dictionary>("Font");
   }
 
   if (!pStreamResFontList->KeyExist(font_name)) {
diff --git a/core/fpdfdoc/cpdf_interactiveform.cpp b/core/fpdfdoc/cpdf_interactiveform.cpp
index 02128d8..a29be97 100644
--- a/core/fpdfdoc/cpdf_interactiveform.cpp
+++ b/core/fpdfdoc/cpdf_interactiveform.cpp
@@ -948,7 +948,7 @@
     pMainDict->SetFor("F", pNewDict);
   }
 
-  CPDF_Array* pFields = pMainDict->SetNewFor<CPDF_Array>("Fields");
+  auto pFields = pMainDict->SetNewFor<CPDF_Array>("Fields");
   CFieldTree::Node* pRoot = m_pFieldTree->GetRoot();
   const size_t nCount = pRoot->CountFields();
   for (size_t i = 0; i < nCount; ++i) {
diff --git a/core/fpdfdoc/cpdf_nametree_unittest.cpp b/core/fpdfdoc/cpdf_nametree_unittest.cpp
index 205c213..78321d5 100644
--- a/core/fpdfdoc/cpdf_nametree_unittest.cpp
+++ b/core/fpdfdoc/cpdf_nametree_unittest.cpp
@@ -29,7 +29,7 @@
 void AddLimitsArray(CPDF_Dictionary* node,
                     const char* least,
                     const char* greatest) {
-  CPDF_Array* limits = node->SetNewFor<CPDF_Array>("Limits");
+  auto limits = node->SetNewFor<CPDF_Array>("Limits");
   limits->AppendNew<CPDF_String>(least, false);
   limits->AppendNew<CPDF_String>(greatest, false);
 }
@@ -69,36 +69,34 @@
 //   {2.txt: 222}      {5.txt: 555}
 //
 void FillNameTreeDict(CPDF_Dictionary* pRootDict) {
-  CPDF_Array* pRootKids = pRootDict->SetNewFor<CPDF_Array>("Kids");
-  CPDF_Dictionary* pKid1 = pRootKids->AppendNew<CPDF_Dictionary>();
+  auto pRootKids = pRootDict->SetNewFor<CPDF_Array>("Kids");
+  auto pKid1 = pRootKids->AppendNew<CPDF_Dictionary>();
 
   // Make the lower and upper limit out of order on purpose.
-  AddLimitsArray(pKid1, "9.txt", "1.txt");
-  CPDF_Array* pKids1Kids = pKid1->SetNewFor<CPDF_Array>("Kids");
-  CPDF_Dictionary* pGrandKid2 = pKids1Kids->AppendNew<CPDF_Dictionary>();
-  CPDF_Dictionary* pGrandKid3 = pKids1Kids->AppendNew<CPDF_Dictionary>();
+  AddLimitsArray(pKid1.Get(), "9.txt", "1.txt");
+  auto pKids1Kids = pKid1->SetNewFor<CPDF_Array>("Kids");
+  auto pGrandKid2 = pKids1Kids->AppendNew<CPDF_Dictionary>();
+  auto pGrandKid3 = pKids1Kids->AppendNew<CPDF_Dictionary>();
 
-  AddLimitsArray(pGrandKid2, "1.txt", "5.txt");
-  CPDF_Array* pGrandKid2Kids = pGrandKid2->SetNewFor<CPDF_Array>("Kids");
-  CPDF_Dictionary* pGreatGrandKid4 =
-      pGrandKid2Kids->AppendNew<CPDF_Dictionary>();
-  CPDF_Dictionary* pGreatGrandKid5 =
-      pGrandKid2Kids->AppendNew<CPDF_Dictionary>();
+  AddLimitsArray(pGrandKid2.Get(), "1.txt", "5.txt");
+  auto pGrandKid2Kids = pGrandKid2->SetNewFor<CPDF_Array>("Kids");
+  auto pGreatGrandKid4 = pGrandKid2Kids->AppendNew<CPDF_Dictionary>();
+  auto pGreatGrandKid5 = pGrandKid2Kids->AppendNew<CPDF_Dictionary>();
 
-  AddLimitsArray(pGrandKid3, "9.txt", "9.txt");
-  CPDF_Array* pNames = pGrandKid3->SetNewFor<CPDF_Array>("Names");
-  AddNameKeyValue(pNames, "9.txt", 999);
+  AddLimitsArray(pGrandKid3.Get(), "9.txt", "9.txt");
+  auto pNames = pGrandKid3->SetNewFor<CPDF_Array>("Names");
+  AddNameKeyValue(pNames.Get(), "9.txt", 999);
 
   // Make the lower and upper limit out of order on purpose.
-  AddLimitsArray(pGreatGrandKid4, "2.txt", "1.txt");
+  AddLimitsArray(pGreatGrandKid4.Get(), "2.txt", "1.txt");
   pNames = pGreatGrandKid4->SetNewFor<CPDF_Array>("Names");
-  AddNameKeyValue(pNames, "1.txt", 111);
-  AddNameKeyValue(pNames, "2.txt", 222);
+  AddNameKeyValue(pNames.Get(), "1.txt", 111);
+  AddNameKeyValue(pNames.Get(), "2.txt", 222);
 
-  AddLimitsArray(pGreatGrandKid5, "3.txt", "5.txt");
+  AddLimitsArray(pGreatGrandKid5.Get(), "3.txt", "5.txt");
   pNames = pGreatGrandKid5->SetNewFor<CPDF_Array>("Names");
-  AddNameKeyValue(pNames, "3.txt", 333);
-  AddNameKeyValue(pNames, "5.txt", 555);
+  AddNameKeyValue(pNames.Get(), "3.txt", 333);
+  AddNameKeyValue(pNames.Get(), "5.txt", 555);
 }
 
 }  // namespace
@@ -106,7 +104,7 @@
 TEST(cpdf_nametree, GetUnicodeNameWithBOM) {
   // Set up the root dictionary with a Names array.
   auto pRootDict = pdfium::MakeRetain<CPDF_Dictionary>();
-  CPDF_Array* pNames = pRootDict->SetNewFor<CPDF_Array>("Names");
+  auto pNames = pRootDict->SetNewFor<CPDF_Array>("Names");
 
   // Add the key "1" (with BOM) and value 100 into the array.
   constexpr char kData[] = "\xFE\xFF\x00\x31";
@@ -154,9 +152,9 @@
 TEST(cpdf_nametree, AddIntoNames) {
   // Set up a name tree with a single Names array.
   auto pRootDict = pdfium::MakeRetain<CPDF_Dictionary>();
-  CPDF_Array* pNames = pRootDict->SetNewFor<CPDF_Array>("Names");
-  AddNameKeyValue(pNames, "2.txt", 222);
-  AddNameKeyValue(pNames, "7.txt", 777);
+  auto pNames = pRootDict->SetNewFor<CPDF_Array>("Names");
+  AddNameKeyValue(pNames.Get(), "2.txt", 222);
+  AddNameKeyValue(pNames.Get(), "7.txt", 777);
 
   std::unique_ptr<CPDF_NameTree> name_tree =
       CPDF_NameTree::CreateForTesting(pRootDict.Get());
@@ -178,17 +176,17 @@
                                          L"9.txt"));
 
   // Check that the names array has the expected key-value pairs.
-  CheckNameKeyValue(pNames, 0, "1.txt", 111);
-  CheckNameKeyValue(pNames, 1, "2.txt", 222);
-  CheckNameKeyValue(pNames, 2, "5.txt", 555);
-  CheckNameKeyValue(pNames, 3, "7.txt", 777);
-  CheckNameKeyValue(pNames, 4, "9.txt", 999);
+  CheckNameKeyValue(pNames.Get(), 0, "1.txt", 111);
+  CheckNameKeyValue(pNames.Get(), 1, "2.txt", 222);
+  CheckNameKeyValue(pNames.Get(), 2, "5.txt", 555);
+  CheckNameKeyValue(pNames.Get(), 3, "7.txt", 777);
+  CheckNameKeyValue(pNames.Get(), 4, "9.txt", 999);
 }
 
 TEST(cpdf_nametree, AddIntoEmptyNames) {
   // Set up a name tree with an empty Names array.
   auto pRootDict = pdfium::MakeRetain<CPDF_Dictionary>();
-  const CPDF_Array* pNames = pRootDict->SetNewFor<CPDF_Array>("Names");
+  auto pNames = pRootDict->SetNewFor<CPDF_Array>("Names");
 
   std::unique_ptr<CPDF_NameTree> name_tree =
       CPDF_NameTree::CreateForTesting(pRootDict.Get());
@@ -214,10 +212,10 @@
                                          L"9.txt"));
 
   // Check that the names array has the expected key-value pairs.
-  CheckNameKeyValue(pNames, 0, "1.txt", 111);
-  CheckNameKeyValue(pNames, 1, "2.txt", 111);
-  CheckNameKeyValue(pNames, 2, "5.txt", 555);
-  CheckNameKeyValue(pNames, 3, "9.txt", 999);
+  CheckNameKeyValue(pNames.Get(), 0, "1.txt", 111);
+  CheckNameKeyValue(pNames.Get(), 1, "2.txt", 111);
+  CheckNameKeyValue(pNames.Get(), 2, "5.txt", 555);
+  CheckNameKeyValue(pNames.Get(), 3, "9.txt", 999);
 }
 
 TEST(cpdf_nametree, AddIntoKids) {
diff --git a/fpdfsdk/cpdfsdk_appstream.cpp b/fpdfsdk/cpdfsdk_appstream.cpp
index cffecbf..5b5550d 100644
--- a/fpdfsdk/cpdfsdk_appstream.cpp
+++ b/fpdfsdk/cpdfsdk_appstream.cpp
@@ -1816,8 +1816,7 @@
 
   RetainPtr<CPDF_Dictionary> pStreamResList =
       pStreamDict->GetOrCreateDictFor("Resources");
-  CPDF_Dictionary* pXObject =
-      pStreamResList->SetNewFor<CPDF_Dictionary>("XObject");
+  auto pXObject = pStreamResList->SetNewFor<CPDF_Dictionary>("XObject");
   pXObject->SetNewFor<CPDF_Reference>(sImageAlias,
                                       widget_->GetPageView()->GetPDFDocument(),
                                       pImage->GetObjNum());
diff --git a/fpdfsdk/cpdfsdk_helpers.cpp b/fpdfsdk/cpdfsdk_helpers.cpp
index c066fe7..a61e430 100644
--- a/fpdfsdk/cpdfsdk_helpers.cpp
+++ b/fpdfsdk/cpdfsdk_helpers.cpp
@@ -236,7 +236,7 @@
       const_cast<CPDF_Array*>(GetQuadPointsArrayFromDictionary(dict)));
 }
 
-CPDF_Array* AddQuadPointsArrayToDictionary(CPDF_Dictionary* dict) {
+RetainPtr<CPDF_Array> AddQuadPointsArrayToDictionary(CPDF_Dictionary* dict) {
   return dict->SetNewFor<CPDF_Array>(kQuadPoints);
 }
 
diff --git a/fpdfsdk/cpdfsdk_helpers.h b/fpdfsdk/cpdfsdk_helpers.h
index be34833..d722ecc 100644
--- a/fpdfsdk/cpdfsdk_helpers.h
+++ b/fpdfsdk/cpdfsdk_helpers.h
@@ -251,7 +251,7 @@
 const CPDF_Array* GetQuadPointsArrayFromDictionary(const CPDF_Dictionary* dict);
 RetainPtr<CPDF_Array> GetMutableQuadPointsArrayFromDictionary(
     CPDF_Dictionary* dict);
-CPDF_Array* AddQuadPointsArrayToDictionary(CPDF_Dictionary* dict);
+RetainPtr<CPDF_Array> AddQuadPointsArrayToDictionary(CPDF_Dictionary* dict);
 bool IsValidQuadPointsIndex(const CPDF_Array* array, size_t index);
 bool GetQuadPointsAtIndex(const CPDF_Array* array,
                           size_t quad_index,
diff --git a/fpdfsdk/fpdf_annot.cpp b/fpdfsdk/fpdf_annot.cpp
index 9861b81..dda378c 100644
--- a/fpdfsdk/fpdf_annot.cpp
+++ b/fpdfsdk/fpdf_annot.cpp
@@ -525,12 +525,11 @@
   if (!safe_ink_size.IsValid<int32_t>())
     return -1;
 
-  CPDF_Array* ink_coord_list = inklist->AppendNew<CPDF_Array>();
+  auto ink_coord_list = inklist->AppendNew<CPDF_Array>();
   for (size_t i = 0; i < point_count; i++) {
     ink_coord_list->AppendNew<CPDF_Number>(points[i].x);
     ink_coord_list->AppendNew<CPDF_Number>(points[i].y);
   }
-
   return static_cast<int>(inklist->size() - 1);
 }
 
@@ -684,7 +683,7 @@
   if (pColor)
     pColor->Clear();
   else
-    pColor.Reset(pAnnotDict->SetNewFor<CPDF_Array>(key));
+    pColor = pAnnotDict->SetNewFor<CPDF_Array>(key);
 
   pColor->AppendNew<CPDF_Number>(R / 255.f);
   pColor->AppendNew<CPDF_Number>(G / 255.f);
@@ -797,7 +796,7 @@
   RetainPtr<CPDF_Array> pQuadPointsArray =
       GetMutableQuadPointsArrayFromDictionary(pAnnotDict.Get());
   if (!pQuadPointsArray)
-    pQuadPointsArray.Reset(AddQuadPointsArrayToDictionary(pAnnotDict.Get()));
+    pQuadPointsArray = AddQuadPointsArrayToDictionary(pAnnotDict.Get());
   AppendQuadPoints(pQuadPointsArray.Get(), quad_points);
   UpdateBBox(pAnnotDict.Get());
   return true;
@@ -967,8 +966,7 @@
   // not use the border values.
   annot_dict->RemoveFor(pdfium::annotation::kAP);
 
-  CPDF_Array* border =
-      annot_dict->SetNewFor<CPDF_Array>(pdfium::annotation::kBorder);
+  auto border = annot_dict->SetNewFor<CPDF_Array>(pdfium::annotation::kBorder);
   border->AppendNew<CPDF_Number>(horizontal_radius);
   border->AppendNew<CPDF_Number>(vertical_radius);
   border->AppendNew<CPDF_Number>(border_width);
@@ -1120,8 +1118,7 @@
 
     // Storing reference to indirect object in annotation's AP
     if (!pApDict) {
-      pApDict.Reset(
-          pAnnotDict->SetNewFor<CPDF_Dictionary>(pdfium::annotation::kAP));
+      pApDict = pAnnotDict->SetNewFor<CPDF_Dictionary>(pdfium::annotation::kAP);
     }
     pApDict->SetNewFor<CPDF_Reference>(modeKey, pDoc,
                                        pNewIndirectStream->GetObjNum());
@@ -1477,7 +1474,7 @@
 
   RetainPtr<CPDF_Dictionary> annot_dict =
       GetMutableAnnotDictFromFPDFAnnotation(annot);
-  CPDF_Dictionary* action = annot_dict->SetNewFor<CPDF_Dictionary>("A");
+  auto action = annot_dict->SetNewFor<CPDF_Dictionary>("A");
   action->SetNewFor<CPDF_Name>("Type", "Action");
   action->SetNewFor<CPDF_Name>("S", "URI");
   action->SetNewFor<CPDF_String>("URI", uri, /*bHex=*/false);
diff --git a/fpdfsdk/fpdf_attachment.cpp b/fpdfsdk/fpdf_attachment.cpp
index b1461bb..de02785 100644
--- a/fpdfsdk/fpdf_attachment.cpp
+++ b/fpdfsdk/fpdf_attachment.cpp
@@ -216,8 +216,7 @@
 
   // Create a dictionary for the new embedded file stream.
   auto pFileStreamDict = pdfium::MakeRetain<CPDF_Dictionary>();
-  CPDF_Dictionary* pParamsDict =
-      pFileStreamDict->SetNewFor<CPDF_Dictionary>("Params");
+  auto pParamsDict = pFileStreamDict->SetNewFor<CPDF_Dictionary>("Params");
 
   // Set the size of the new file in the dictionary.
   pFileStreamDict->SetNewFor<CPDF_Number>(pdfium::stream::kDL,
@@ -244,8 +243,7 @@
   memcpy(stream.get(), contents, len);
   auto pFileStream = pDoc->NewIndirect<CPDF_Stream>(std::move(stream), len,
                                                     std::move(pFileStreamDict));
-  CPDF_Dictionary* pEFDict =
-      pFile->AsMutableDictionary()->SetNewFor<CPDF_Dictionary>("EF");
+  auto pEFDict = pFile->AsMutableDictionary()->SetNewFor<CPDF_Dictionary>("EF");
   pEFDict->SetNewFor<CPDF_Reference>("F", pDoc, pFileStream->GetObjNum());
   return true;
 }
diff --git a/fpdfsdk/fpdf_catalog_unittest.cpp b/fpdfsdk/fpdf_catalog_unittest.cpp
index 690f012..dd765bf 100644
--- a/fpdfsdk/fpdf_catalog_unittest.cpp
+++ b/fpdfsdk/fpdf_catalog_unittest.cpp
@@ -56,8 +56,7 @@
   EXPECT_FALSE(FPDFCatalog_IsTagged(m_pDoc.get()));
 
   // Root with empty MarkInfo
-  CPDF_Dictionary* markInfoDict =
-      m_pRootObj->SetNewFor<CPDF_Dictionary>("MarkInfo");
+  auto markInfoDict = m_pRootObj->SetNewFor<CPDF_Dictionary>("MarkInfo");
   EXPECT_FALSE(FPDFCatalog_IsTagged(m_pDoc.get()));
 
   // MarkInfo present but Marked is 0
diff --git a/fpdfsdk/fpdf_editpage.cpp b/fpdfsdk/fpdf_editpage.cpp
index c88ecfb..0611a57 100644
--- a/fpdfsdk/fpdf_editpage.cpp
+++ b/fpdfsdk/fpdf_editpage.cpp
@@ -705,7 +705,7 @@
     if (pRectArray)
       pRectArray->Clear();
     else
-      pRectArray.Reset(pAnnotDict->SetNewFor<CPDF_Array>("Rect"));
+      pRectArray = pAnnotDict->SetNewFor<CPDF_Array>("Rect");
 
     pRectArray->AppendNew<CPDF_Number>(rect.left);
     pRectArray->AppendNew<CPDF_Number>(rect.bottom);
diff --git a/fpdfsdk/fpdf_edittext.cpp b/fpdfsdk/fpdf_edittext.cpp
index 2b61d1a..38b7cf8 100644
--- a/fpdfsdk/fpdf_edittext.cpp
+++ b/fpdfsdk/fpdf_edittext.cpp
@@ -441,7 +441,7 @@
 
   // TODO(npm): Support vertical writing
 
-  auto* pDescendant = pFontDict->SetNewFor<CPDF_Array>("DescendantFonts");
+  auto pDescendant = pFontDict->SetNewFor<CPDF_Array>("DescendantFonts");
   pDescendant->AppendNew<CPDF_Reference>(pDoc, pCIDFont->GetObjNum());
 
   CPDF_Stream* toUnicodeStream = LoadUnicode(pDoc, to_unicode);
diff --git a/fpdfsdk/fpdf_flatten.cpp b/fpdfsdk/fpdf_flatten.cpp
index 2b0e18a..202ec82 100644
--- a/fpdfsdk/fpdf_flatten.cpp
+++ b/fpdfsdk/fpdf_flatten.cpp
@@ -317,7 +317,7 @@
 
   SetPageContents(key, pPageDict.Get(), pDocument);
 
-  CPDF_Dictionary* pNewXORes = nullptr;
+  RetainPtr<CPDF_Dictionary> pNewXORes;
   if (!key.IsEmpty()) {
     pPageXObject->SetNewFor<CPDF_Reference>(key, pDocument,
                                             pNewXObject->GetObjNum());