scopchanov
scopchanov

Reputation: 8419

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

I would like to ask the following:

Suppose that we have three classes in C++: A, B and C. An object of class A is creating and owning an object of class B. It is then giving the reference of B to an object of class C to be stored as a pointer variable. So, what is the best practice to inform C, that the pointer to B is no longer valid (and should be set to null), if A is deleted?

Is there a general approach or for example a Qt specific one?

Upvotes: 0

Views: 69

Answers (1)

anorm
anorm

Reputation: 2263

Use std::weak_ptr

Example (live demo here)

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

Upvotes: 3

Related Questions