簡體   English   中英

unique_ptr 沒有操作刪除

[英]No op delete for unique_ptr

將 unique_ptr 傳遞給不執行任何操作的自定義刪除器的最簡潔方法是什么? 我需要一個我正在編寫的 JNI 函數,其中 C++ 端需要一個 unique_ptr,但是,我不希望在退出 JNI 函數時刪除 unique_ptr 持有的對象 - 我稍后會處理刪除。 所以我想做類似的事情:

std::unique_ptr<MyClass, noop_delete> ptr;

在一行中 - 沒有單獨的函數定義:-)

正如@ 101010指出的那樣, std::unique_ptr帶有nop刪除器是非常奇怪的,因為std::unique_ptr唯一有價值的東西實際上就是刪除器。 另外,你說“C ++方面需要一個unique_ptr”,但是帶有不同刪除器的std::unique_ptr將是一個不同的類型 ,這可能不起作用。

不過,這是做到這一點的方法:

struct nop
{
    template <typename T>
    void operator() (T const &) const noexcept { }
};

template <typename T>
using nop_unique_ptr = std::unique_ptr<T, nop>;

請注意,此nop類型可以在任何地方用作無操作,而不是單參數仿函數。

我在答案中對@ lisyarus的問題的回答促使我提出了一個比我給那里更好的解決方案。 這本書以已經@lisyarus陳述的事實:無操作刪除器unique_ptr是不同類型比的unique_ptr具有delete刪除器。

我將此作為單獨的答案發布,因為它可能與其他人相關(此外,這不適合單個評論)。

上下文 :對於單元測試,FakeIt模擬框架管理模擬對象的生命周期,因此當需要模擬通過unique_ptr指向的對象時,我們需要帶有no-op刪除器的unique_ptr。

// As in @lisyarus's answer...
struct nop
{
    template <typename T>
    void operator() (T const &) const noexcept { }
};

// NOTE: We have no use for a pointer that doesn't delete unless we're mocking, so 
// the types below are named to indicate that.

#ifndef WE_ARE_BUILDING_UNIT_TESTS
// Production build - we want a unique_ptr that deletes.
template <typename T>
using mockable_unique_ptr = std::unique_ptr<T>;
#else
// Unit test build - we want unique_ptr that doesn't delete.
template <typename T>
using mockable_unique_ptr = std::unique_ptr<T, nop>;
#endif

現在,mockable_unique_ptr將根據構建類型自動切換類型,這意味着您不必在代碼上遍布#ifdefs。 當然,你需要某些位置#ifdef /#else,並使用稍微不同的代碼進行單元測試構建(可能在指針初始化的站點,但如果你的mock也在那里創建,你需要反正這樣做)。 然而,其余代碼保持不變,因為unique_ptr的接口不會改變。

std::unique_ptr::release怎么樣?

void JNIfunc (T*) {};
std::make_unique( new T) t;
JNIfunc( t.release);

暫無
暫無

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

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