开发者

boost::shared_?? for non-pointer resources

开发者 https://www.devze.com 2023-02-12 00:10 出处:网络
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

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
}


Allocate NonPointerResource on the heap and just give it a destructor as normal.


Maybe boost::intrusive_ptr could fit the bill. Here's a RefCounted base class and ancillary functions that I'm using in some of my code. Instead of delete ptr you can specify whatever operation you need.

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; }

With that in place you can then have

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


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消