簡體   English   中英

將帶有自定義刪除器的unique_ptr移動到shared_ptr

[英]Move a unique_ptr with custom deleter to a shared_ptr

我有一個函數,它使用自定義刪除器創建unique_ptr並返回它:

auto give_unique_ptr() {
    auto deleter = [](int* pi) {
        delete pi;
    };
    int* i = new int{1234};
    return std::unique_ptr<int, decltype(deleter)>(i, deleter);
}

在該函數的客戶端代碼中,我想將unique_ptr移動到shared_ptr ,但我不知道該怎么做,因為我不知道函數之外的自定義刪除器的decltype。

我想它應該看起來像這樣:

auto uniquePtr = give_unique_ptr();
auto sharedPtr = std::shared_ptr<..??..>(std::move(uniquePtr));

我需要寫什么而不是.. ?? ..來獲得正確的類型?

如果這是可能的,那么shared_ptr會很好地運行並且當它的使用計數達到零時調用在give_unique_ptr()函數內創建的自定義刪除器嗎?

如果您知道(或想要顯式鍵入)對象的類型 ,那么您可以這樣做:

std::shared_ptr<int> sharedPtr(std::move(uniquePtr));

std::shared_ptr的構造函數將處理deletor。


但是,如果您想要推斷類型 ,那么:

auto sharedPtr = make_shared_from(std::move(uniquePtr));

make_shared_from是:

template<typename T, typename D>
std::shared_ptr<T> make_shared_from(std::unique_ptr<T,D> && p)
{
   //D is deduced but it is of no use here!
   //We need only `T` here, the rest will be taken 
   //care by the constructor of shared_ptr
   return std::shared_ptr<T>(std::move(p));
};

希望有所幫助。

auto uniquePtr = give_unique_ptr();
auto sharedPtr = std::shared_ptr<decltype(uniquePtr)::element_type>(std::move(uniquePtr));

是的, shared_ptr將存儲 - 以后使用 - 自定義刪除器。

暫無
暫無

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

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