簡體   English   中英

如何僅將shared_ptr用於刪除器?

[英]How to use a shared_ptr for the deleter only?

我只想在不使用shared_ptr部分的情況下使用shared_ptr的刪除功能。 就像在,我想在shared_ptr超出范圍並且刪除器不需要傳遞給它的任何指針時調用一個函數。

我有這個,但它很靦腆。

shared_ptr<int> x(new int, [&](int *me) { delete me; CloseResource(); }); 

有沒有辦法不將任何指針與shared_ptr關聯?

更新:根據許多建議,unique_ptr方式如下所示:

unique_ptr<int, std::function<void(int*)>> x(new int, [&](int *me) {delete me; CloseResource();});

坦率地看起來比shared_ptr版本更糟糕,盡可能多“好”。

更新:對於那些喜歡使用這個簡單范圍關閉函數調用者的人,我使它更簡單一點,你甚至不需要分配或釋放一個對象:

shared_ptr<int> x(NULL, [&](int *) { CloseResource(); });

聽起來你可能要做的就是將“刪除”責任轉交給“別人”,這樣你就不用再擔心了。 如果是這種情況,帶有自定義刪除器的unique_ptr (不是shared_ptr )將起作用:

struct Foo final {};
Foo* New() { return new Foo; }
void Delete(Foo* p) { delete p; }

int main()
{
    auto p = New();
    std::unique_ptr<Foo, decltype(&Delete)> up(p, &Delete);
}

有多家上市類似的解決方案在這里 ; 如果沒有關於你的實際API的更多信息,可以做更多的事情(例如, HANDLE真的是指針技巧嗎?)。 更多閱讀最簡單,最新的c ++ 11 ScopeGuard ,包括指向 std::unique_resource鏈接

如果你想要一個像lambda這樣語義的RAII可能會這樣做嗎?

namespace details {
  enum class ScopeExitDummy { };
}


template<typename T>
class scope_exit_t
{
public:
  inline scope_exit_t(T&& codeChunk_)
    : m_codeChunk(std::forward<T>(codeChunk_)) {
  }

  inline scope_exit_t(scope_exit_t<T>&& rhs_)
    : m_codeChunk(std::move(rhs_.m_codeChunk))
  {
  }

  ~scope_exit_t() {
    m_codeChunk();
  }

private:
  T m_codeChunk;
};

template<typename T>
inline scope_exit_t<T> operator+(details::ScopeExitDummy, T&& functor_) {
  return scope_exit_t<T>{std::forward<T>(functor_)};
}

#define AtScopeExit auto TW_UNIQUE_VARIABLE(_scopeExit) = details::ScopeExitDummy{} + [&]

用法如下:

AtScopeExit {
  CloseResource();
};

注意:TW_UNIQUE_VARIABLE只是一個生成唯一變量名的宏,因此代碼不會與手寫聲明沖突。

#define TW_STR_CONCAT_IMPL(x, y) x##y
#define TW_STR_CONCAT(x, y) TW_STR_CONCAT_IMPL(x, y)

#ifdef __COUNTER__
  #define TW_UNIQUE_VARIABLE(prefix) TW_STR_CONCAT(prefix, __COUNTER__)
#else
  #define TW_UNIQUE_VARIABLE(prefix) TW_STR_CONCAT(prefix, __LINE__)
#endif

暫無
暫無

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

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