![](/img/trans.png)
[英]How to use smart pointer (e.g. auto_ptr r shared_ptr) to generate a link list data structure in C++ on Linux?
[英]Smart pointer analog of `std::shared_ptr` with API to bind callbacks to refcount-modifying events e.g. release/retain … is this a thing?
我需要一個智能指針結構 - 類似於std::shared_ptr
- 它為我提供了一些帶有暴露掛鈎的API,對其進行refcount修改事件的回調(例如release / retain,aka refcout increment / decrement)可以綁定。
我想要自己實現,或者使用現成的東西,如果存在的話。
就像,我想最好能夠說“在你定義這個假定的shared_ptr
-ish智能指針的時候,每當你遞增引用數量時調用這個可調用數量[但是在減少時那個調用]”(就像分別使用delete-expressions和deleter functor一樣) ,在shared_ptr
和unique_ptr
定義中)。
編輯(從我下面的評論) - 這就是我想要這個的原因:我目前有一個Image類模板,它的核心是std :: shared_ptr,它包含一個(可能很大的)連續堆分配的內存塊。 Image具有實現hyperslab迭代器(暴露例如顏色平面,CBIR散列數據和c)的內部類,這些內部類使用std :: weak_ptr來引用返回擁有的Image實例的內存塊。 我想為特定的refcounted運行時擴展Image - 例如Python c-api - 並且綁定到現有的std :: shared_ptr refcounter設備比保持兩個不同的系統同步更可取。
shared_ptr
的默認實現有shared_ptr
,它們共享一個對象,所有對象都指向一個所謂的控制塊。 正是這個控制塊保存了參考計數器,因此是更自然地可以對參考計數變化作出反應的對象。
但是,如果您真的想通過智能指針進行操作,則可能會有以下情況:
using std::shared_ptr;
template<class T> class sharedX_ptr;
// the type of function to call when a refcount change happens
template<class T>
void inc_callback(const sharedX_ptr<T>& p)
{
std::cout << "Increasing refcount via " << &p
<< ", for object: " << p.get() << ", use_count: " << p.use_count()
<< std::endl;
}
template<class T>
void dec_callback(const sharedX_ptr<T>& p)
{
std::cout << "About to decrease refcount via " << &p
<< ", for object: " << p.get() << ", use_count: " << p.use_count()
<< std::endl;
}
template<class T>
class sharedX_ptr : public shared_ptr<T>
{
typedef void (*callback)(const sharedX_ptr<T>&);
callback inc, dec;
public:
typedef shared_ptr<T> base;
sharedX_ptr(const sharedX_ptr& p) : base(p), inc(p.inc), dec(p.dec)
{ if (this->get()) inc(*this); }
template<class U>
sharedX_ptr(sharedX_ptr<U>&& p) : base(std::move(p)), inc(p.inc), dec(p.dec)
{ /*if (this->get()) inc(*this);*/ }
template<class U>
sharedX_ptr(shared_ptr<U> p, callback i = inc_callback<T>, callback d = dec_callback<T>)
: shared_ptr<T>(std::move(p)), inc(i), dec(d)
{ if (this->get()) inc(*this); }
sharedX_ptr& operator=(sharedX_ptr&& p) {
if (this != &p) {
if (this->get()) dec(*this);
base::operator=(std::move(p)); inc = p.inc; dec = p.dec;
/* if (this->get()) inc(*this); */
}
return *this;
}
template<class U>
sharedX_ptr& operator=(const sharedX_ptr& p) {
if (this != &p) {
if (this->get()) dec(*this);
base::operator=(p); inc = p.inc; dec = p.dec;
if (this->get()) inc(*this);
}
return *this;
}
void reset() { if (this->get()) dec(*this); shared_ptr<T>::reset();}
~sharedX_ptr() { if (this->get()) dec(*this); }
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.