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

lur*_*her 2 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
}
Run Code Online (Sandbox Code Playgroud)

Pup*_*ppy 5

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