开发者

Smart pointers in C++ with shared object-validation

I need smart pointer class or template, which can invalidate it's referencing object after 'delete' happens. Key point is to make pointer usable in debug for multy-thread apps.

Here is an example, just pseudocode:

void foo1(smart_ptr<myclass> ptr)
{
    //some code
    delete ptr;
    //some other code
}

void foo2(smart_ptr<myclass> ptr)
{
    //some code
    function_wich_uses_ptr(ptr);
    //some other code
}


int main()
{
    myclass val = new myclass();
    smart_ptr<myclass> ptr(&val);
    //somehow make a copy of ptr
    smart_ptr<myclass> ptr2(ptr);
    //some code
    thread_start(foo1, ptr);
    thread_start(foo2, ptr2);
    //
    return 0;
}

So, I need foo2 somehow to track if foo1 has already deleted object referenced to ptr. In general - after anyone of 'living' smart pointers to a single obect deletes that object, all the other pointers to the same object should somehow 'feel' it and set it's own value to开发者_开发知识库 NULL.

UPD my bad, example was incorrect


You are looking for a non-owning smart-pointer. This is exactly what boost::weak_ptr does.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜