提高:: shared_?对于非指针资源

时间:2011-02-20 14:12:59

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

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

我需要做的例子:

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
}

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:4)

也许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 = ...

答案 2 :(得分:1)

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

相关问题