![](/img/trans.png)
[英]Why does unique_ptr have the deleter as a type parameter while shared_ptr doesn't?
[英]Why unique_ptr with custom deleter won't work for nullptr, while shared_ptr does?
使用unique_ptr
或shared_ptr
作為范圍保護的簡單代碼。 有關清除內容的所有信息都在deleter
捕獲,因此我盡管將nullptr
用於構造函數是安全的。
顯然,使用Visual C ++ 2017(14.1),它不能像unique_ptr
那樣工作,但適用於shared_ptr
。 這是微軟的怪癖,還是標准阻止在持有nullptr
時調用unique_ptr
的deleter
?
在下面的代碼中,我被迫用(void*)1
構造一個unique_ptr
。 如果我使用nullptr
構造它,則不會調用cleaner
。 對於shared_ptr
,沒有區別,總是調用cleaner
。
#include <memory>
#include <iostream>
int main()
{
int ttt = 77;
auto cleaner = [&ttt](void*) {
std::cout << "cleaner: " << ttt << "\n"; // do something with capture here instead of print
};
std::unique_ptr<void, decltype(cleaner)> p((void*)1, cleaner);
std::shared_ptr<void> q(nullptr, [&ttt](void*) {
std::cout << "shared: " << ttt << "\n"; // do something with capture here instead of print
});
std::cout << "done\n";
return 0;
}
unique_ptr
的析構函數需要這樣做:
23.11.1.2.2 unique_ptr析構函數[unique.ptr.single.dtor]
2效果:如果
get() == nullptr
沒有效果。 否則get_deleter()(get())
。
實際上shared_ptr
的析構函數需要執行相同的操作:
23.11.2.2.2 shared_ptr析構函數[util.smartptr.shared.dest]
- (1.1)如果
*this
為空或與另一個shared_ptr
實例共享所有權(use_count() > 1
),則沒有副作用。- (1.2)否則,如果
*this
擁有對象p和刪除器d,則調用d(p)。
所以依靠智能指針在傳遞空指針時在范圍出口執行任意操作是不可靠的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.