在c++中,通知引用对象被删除

Informing the referencing object that the referred one is deleted in C++

本文关键字:对象 删除 引用 通知 c++      更新时间:2023-10-16

我想问以下问题:

假设c++中有三个类:A、B和C。A类的对象创建并拥有B类的对象,然后将B类的引用作为指针变量存储给C类的对象。那么,如果A被删除,通知C指向B的指针不再有效(并且应该设置为null)的最佳实践是什么?

是否有一个通用的方法或例如一个特定的Qt ?

使用std::weak_ptr

示例(现场演示)

class A
{
private:
    std::shared_ptr<B> myB;
public:
    A() :
      myB(std::make_shared<B>())
    {
    }
    std::weak_ptr<B> GetB()
    {
        return myB;
    }
};
class B
{
};
class C
{
private:
    std::weak_ptr<B> theB;
public:
    C(std::weak_ptr<B> b) :
      theB(b)
    {
    }
    void test()
    {
        auto b = theB.lock();
        if (b)
        {
            // theB is still valid
        }
        else
        {
            // theB is gone
        }
    }
};