簡體   English   中英

為什么帶有自定義刪除器的unique_ptr對於nullptr不起作用,而shared_ptr呢?

[英]Why unique_ptr with custom deleter won't work for nullptr, while shared_ptr does?

使用unique_ptrshared_ptr作為范圍保護的簡單代碼。 有關清除內容的所有信息都在deleter捕獲,因此我盡管將nullptr用於構造函數是安全的。

顯然,使用Visual C ++ 2017(14.1),它不能像unique_ptr那樣工作,但適用於shared_ptr 這是微軟的怪癖,還是標准阻止在持有nullptr時調用unique_ptrdeleter

在下面的代碼中,我被迫用(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.

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