Search code examples
c++boostraiireference-countingshared-ptr

boost::shared_?? for non-pointer resources


Basically i need to do reference counting on certain resources (like an integer index) that are not inmediately equivalent to a pointer/address semantic; basically i need to pass around the resource around, and call certain custom function when the count reaches zero. Also the way to read/write access to the resource is not a simple pointer derreference operation but something more complex. I don't think boost::shared_ptr will fit the bill here, but maybe i'm missing some other boost equivalent class i might use?

example of what i need to do:

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
}

Solution

  • Here is a small example about the use of shared_ptr<void> as a counted handle.
    Preparing proper create/delete functions enables us to use shared_ptr<void> as any resource handle in a sense.
    However, as you can see, since this is weakly typed, the use of it causes us inconvenience in some degree...