C++中具有共享对象验证的智能指针

Smart pointers in C++ with shared object-validation

本文关键字:验证 智能 指针 对象 共享 C++      更新时间:2023-10-16

我需要智能指针类或模板,它可以在"删除"发生后使其引用对象无效。关键是使指针在多线程应用程序的调试中可用。

这里有一个例子,只是伪代码:

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

所以,我需要foo2以某种方式跟踪foo1是否已经删除了引用到ptr的对象。一般来说,在指向单个obect的任何"活动"智能指针删除该对象后,指向同一对象的所有其他指针都应该以某种方式"感觉"到它,并将它自己的值设置为NULL。

UPD我的错误,例如不正确

您正在寻找一个没有所有权的智能指针。这正是boost::weak_ptr所做的。