智能指针模拟“std::shared_ptr”,带有 API 将回调绑定到引用计数修改事件,例如释放/保留……这是一件事吗?

fis*_*000 5 c++ pointers smart-pointers shared-ptr c++11

我需要一个智能指针结构 \xe2\x80\x93 类似于std::shared_ptr xe2\x80\x93 ,它为我提供某种带有暴露钩子的 API,回调引用计数修改事件(例如释放/保留,又名 refcout 增量/减量)可以绑定。

\n\n

我要么想自己实现这个,要么使用现成的东西(如果存在的话)。

\n\n

就像,我希望最好能够说 \xe2\x80\x9c 每当你增加引用计数时调用这个可调用的[但在递减时]\xe2\x80\x9d 同时定义这个假定的 -ishshared_ptr智能指针(就像删除 -表达式和删除函子分别用于shared_ptrunique_ptr)。

\n\n
\n\n

编辑(来自我下面的评论) \xe2\x80\x93 Here\xe2\x80\x99s 为什么我想要这个:我目前有一个 Image 类模板,其核心有一个 std::shared_ptr 持有一个(可能很大)连续的堆分配内存块。Image 具有实现 hyperslab 迭代器(公开例如颜色平面、CBIR 哈希数据等)的内部类,这些迭代器使用 std::weak_ptr 来引用所属 Image 实例的内存块。我想为特定的引用计数运行时 \xe2\x80\x93 扩展 Image,例如 Python c-api \xe2\x80\x93 并绑定到现有的 std::shared_ptr refcounter 设备比保持两个不同的系统同步更可取。

\n

hkB*_*Bst 2

shared_ptrhas的默认实现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); }
};
Run Code Online (Sandbox Code Playgroud)