2

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

我需要做的例子:

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

3 回答 3

5

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

于 2011-02-20T14:19:22.617 回答
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 = ...
于 2011-02-20T14:40:26.227 回答
1

是一个关于shared_ptr<void>用作计数句柄的小例子。
准备适当的创建/删除函数使我们能够 在某种意义上shared_ptr<void>用作任何资源句柄。
然而,正如你所看到的,由于这是弱类型,它的使用在某种程度上给我们带来了不便......

于 2011-02-20T21:26:36.683 回答