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

基本上我需要对某些资源(如整数索引)进行引用计数,这些资源并不等同于指针/地址语义;基本上我需要传递资源,并在计数达到零时调用某些自定义函数。读取/写入资源的方式也不是简单的指针引用操作,而是更复杂的操作。我不认为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
}
    
已邀请:
这里 关于使用
shared_ptr<void>
作为计数句柄的一个小例子。 准备正确的创建/删除功能使我们能够使用
shared_ptr<void>
在某种意义上作为任何资源句柄。 但是,正如您所看到的,由于这是弱类型的,因此使用它会导致我们 在某种程度上带来的不便......     
在堆上分配NonPointerResource并正常给它一个析构函数。     
也许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 = ...
    

要回复问题请先登录注册