【问题标题】:boost::shared_?? for non-pointer resourcesboost::shared_??对于非指针资源
【发布时间】:2011-02-20 14:12:59
【问题描述】:

基本上我需要对某些资源(如整数索引)进行引用计数,这些资源并不直接等同于指针/地址语义;基本上我需要传递资源,并在计数达到零时调用某些自定义函数。此外,对资源的读/写访问不是简单的指针取消引用操作,而是更复杂的操作。我不认为 boost::shared_ptr 适合这里的账单,但也许我错过了我可能使用的其他一些 boost 等效类?

我需要做的例子:

struct NonPointerResource
{
   NonPointerResource(int a) : rec(a) {} 

   int rec;
}

int createResource ()
{
   data BasicResource("get/resource");
   boost::shared_resource< MonPointerResource > r( BasicResource.getId() , 
    boost::function< BasicResource::RemoveId >() );
   TypicalUsage( r );
}  
//when r goes out of scope, it will call BasicResource::RemoveId( NonPointerResource& ) or something similar


int TypicalUsage( boost::shared_resource< NonPointerResource > r )
{
   data* d = access_object( r );
   // do something with d
}

【问题讨论】:

  • 仅供参考,here 是一个关于使用 shared_ptr&lt;void&gt; 作为计数句柄的小示例。但不幸的是,这肯定没有理想的可用性......
  • @Ise,请将其写为答案,以便我可以将其设置为接受的答案

标签: c++ boost raii reference-counting shared-ptr


【解决方案1】:

在堆上分配 NonPointerResource 并像往常一样给它一个析构函数。

【讨论】:

  • 这通常是最好的解决方案,因为它将引用计数(这不是微不足道的,特别是如果它是线程安全的)与资源管理分开。然后NonPointerResource 类可能是不可复制的,除非底层资源有明确定义的复制语义。
【解决方案2】:

也许 boost::intrusive_ptr 可以满足要求。这是我在一些代码中使用的RefCounted 基类和辅助函数。您可以指定您需要的任何操作,而不是 delete ptr

struct RefCounted {
    int refCount;

    RefCounted() : refCount(0) {}
    virtual ~RefCounted() { assert(refCount==0); }
};

// boost::intrusive_ptr expects the following functions to be defined:
inline
void intrusive_ptr_add_ref(RefCounted* ptr) { ++ptr->refCount; }

inline
void intrusive_ptr_release(RefCounted* ptr) { if (!--ptr->refCount) delete ptr; }

有了这些,你就可以拥有了

boost::intrusive_ptr<DerivedFromRefCounted> myResource = ...

【讨论】:

  • 计数不必是mutable
  • 是的,我想知道这一点——我只是从我拥有的一些工作代码中粘贴了它。可变的现已移除。
【解决方案3】:

Here 是一个关于使用shared_ptr&lt;void&gt; 作为计数句柄的小例子。
准备适当的创建/删除功能使我们能够使用 shared_ptr&lt;void&gt; 在某种意义上作为任何资源句柄。
但是,正如您所看到的,由于这是弱类型,因此使用它会导致我们 某种程度上的不便……

【讨论】:

  • 是的。访问资源也将是一个问题,但没有出路。谢谢
  • @lurscher:很高兴能帮上忙 :-)
猜你喜欢
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 2015-02-03
  • 2021-06-05
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多