首頁  >  文章  >  後端開發  >  為什麼在建立 std::unique_ptr 物件時 std::make_unique 優於 New 運算子?

為什麼在建立 std::unique_ptr 物件時 std::make_unique 優於 New 運算子?

Barbara Streisand
Barbara Streisand原創
2024-10-28 01:59:31746瀏覽

 Why Is std::make_unique Preferred Over the New Operator for Creating std::unique_ptr Objects?

為什麼在新運算子上使用 std::make_unique 來指派 std::unique_ptr?

建立 std:: 時unique_ptr 對象,建議使用 std::make_unique 而不是 new 運算子。以下是使用std::make_unique 的主要優點:

改進的語法

std::make_unique 簡化了初始化語法,要求物件的類型只被提及一次。這樣可以讓程式碼更簡潔,不易出現錯字。

方便封裝

std::make_unique 封裝了分配和初始化過程,更方便且容易出錯。它一步管理記憶體分配並分配給 std::unique_ptr。

異常安全

std::make_unique 是異常安全的,這意味著它可以優雅地處理物件分配期間可能發生的異常。如果在分配過程中拋出異常,std::make_unique 會確保分配的記憶體被正確清理,防止記憶體洩漏。

避免未指定的求值順序

使用 std::make_unique 有助於避免未指定的評估順序問題。涉及 new 和 unique_ptr 的表達式的求值順序可能有問題,可能導致記憶體洩漏。 std::make_unique 確保在執行任何其他操作之前將物件正確指派並指派給 unique_ptr。

缺點:

  • 自訂刪除器:如果您需要為 unique_ptr 物件使用自訂刪除器,則不能使用 std::make_unique。
  • 採用原始指針:如果您採用來自其他來源的原始指針,則不能使用 std::make_unique直接。

以上是為什麼在建立 std::unique_ptr 物件時 std::make_unique 優於 New 運算子?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn