簡體   English   中英

在堆上分配shared_ptr可能會發生內存泄漏?

[英]Is there might be memory leak to allocate shared_ptr on the heap?

剛剛閱讀此帖子stdshared-ptr-exception-safety

因此以下代碼不會發生內存泄漏:

std::shared_ptr<int> p3 (new int);

但是如何跟隨一個:

func(new std::shared_ptr<int>(new int));

如果shared_ptr的分配拋出bad_alloc異常,並且已經評估了“新整數”,則我認為該int被泄漏了。 他們是否標准定義了new std::shared_ptr需要首先分配內存,然后評估參數new int

是的,那是潛在的內存泄漏。

但是,這是std::shared_ptr的非常常規的用法。 通常, shared_ptr保留在自動存儲中(在堆棧上)以利用RAII。

是的,它可能會泄漏。

如果new std::shared_ptr拋出,則沒有任何東西可以清理new int分配的內存。

通常,僅當構造函數在相應的new之后拋出時才進行自動delete調用。

要詳細說明,您可以按以下方式重寫代碼:

// if 'new' throws, we just get a bad_alloc, nothing leaked
int *iptr = new int;

// if 'new' throws, nothing will clean up iptr
//
// if, for whatever reason, ctor of std::shared_ptr<int> throws,
// its memory gets reclaimed by an implicit delete, but iptr's target
// is still lost.
auto *ptrptr = new std::shared_ptr<int>(iptr);

// EDIT: If the constructor of shared_ptr fails, it will delete
// the memory it is given, though this still doesn't eliminate the
// leak that can occur if the above `new` fails.

編輯:

上面的示例以及這種解釋,實際上是要表明std::shared_ptr與任何其他智能指針實現相比,沒有什么特別的地方,或者某種接受指針作為構造函數參數的類型。

在后一種情況下,它實際上取決於類型的構造函數對其參數進行的處理。 std::shared_ptr的情況下,它很可能不會拋出異常,除非它未能分配控制塊(實際上,實際上是如何實現)。

如果std::shared_ptr的構造函數確實失敗了,至少對於我正在使用的實現(VS2012),它實際上確實刪除了給定的內存。

如果shared_ptr的分配拋出bad_alloc異常並且已經評估了new int ,則我認為該int被泄漏了。

是的,如果按該順序進行求值,並且共享指針分配失敗,則整數將泄漏。

他們是否標准定義了new std::shared_ptr需要首先分配內存,然后評估參數new int

不,按照C ++ 11 5.3.4 / 16的規定,它們的順序不確定。

因此,動態分配智能指針不僅危險而且令人困惑,這是危險的。 不要這樣

可能導致內存泄漏,並且是不安全的。 分配的std::shared_ptr本身應在某處進行保護。 shared_ptr可能會引發異常,因此您應該處理該異常。 new std::shared_ptr也可能引發異常,您也應該處理該異常。 第一個例外不會導致內存泄漏,但是第二個例外。

另一方面,您無需動態分配std::shared_ptr 它沒有優勢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM