Search code examples
c++smart-pointersdatamember

Using smart pointers to keep track of data members that may be deleted


I have two classes A and B. I compute a B deterministically from an A. For each A, I want to keep track of the B with my_B for as long as it exists. Once the B is destructed, I want the my_B to be changed to something like nullptr.

class A{
// stuff
public:
    B ComputeB(){
        if (my_B is null){
            B result = B(A);
            my_B = B; // some kind of reference
            return B(A);
        } 
        else {
            return my_B;
        }
    }
    
    ~A(){  /* Do I need a destructor? */ }
private:
    WhatTypeHere my_B;
}

When B is destructed, what will cause my_B to refer to nullptr (or the equivalent for WhatTypeHere)?


Solution

  • You can return a std::shared_ptr from ComputeB(), and make my_B a std::weak_ptr. Something like this:

    std::shared_ptr<B> ComputeB() {
        if (my_B.expired()) {
            auto result = std::make_shared<B>(*this);
            my_B = result;
            return result;
        } else {
            return std::shared_ptr<B>(my_B);
        }
    }
    
    private:
    std::weak_ptr<B> my_B;
    

    The idea is that any caller of ComputeB becomes the partial owner of the B instance, which means that it will only be destroyed when all shared_ptrs to it are destroyed. The purpose of the weak_ptr is to point to the B instance without owning it, so the lifetime isn't tied to the A instance at all