Approach for one class to safely refer to another, with both having unknown lifetimes It is not always possible to simplify program design by strictly managing the lifetimes of objects. If two objects have unpredictable lifetimes, but one of them needs to refer to the other, a simple pointer or reference is a segmentation fault waiting to happen.

The approach that I tried first was to have both objects contain a pointer to the other, and code in the destructors of both objects that would set the other object's pointer to null:

#include &lt;iostream&gt;

class Manager;

class Tracked
{
public:
    ~Tracked();
    void act() {std::cout &lt;&lt; "hello world!\n";}
    void setManager(Manager *manager) {manager_ = manager;}
    void markManagerInvalid() {manager_ = nullptr;}
private:
    Manager *manager_;
};

class Manager
{
public:
    void attach(Tracked &amp;tracked)
    {
        tracked_ = &amp;tracked;
        tracked_-&gt;setManager(this);
    }
    void detach()
    {
        if(tracked_ != nullptr)
        {
            tracked_-&gt;markManagerInvalid();
            tracked_ = nullptr;
        }
    }
    void invoke()
    {
        if(tracked_ != nullptr)
            tracked_-&gt;act();
    }
private:
    Tracked *tracked_;
};

Tracked::~Tracked()
{
    if(manager_ != nullptr)
        manager_-&gt;detach();
}

int main()
{
    Manager manager;
    {
        Tracked tracked;
        manager.attach(tracked);
        manager.invoke(); //output: hello world!
    }//"tracked" goes out of scope: the pointer in "manager" is now invalidated.
    manager.invoke();
}


This works and sounds very simple but in practice it has serious drawbacks:


There is not only tight coupling but also a circular dependency between Tracker and Manager.
In order to have many Manager instances link to the same Tracked instance, the Tracked class would have to incorporate a list of Manager pointers to instances that are linking to it.
The code is complex and error prone, and would get even worse with multiple instances linking to each other.


To get around this I devised a different solution: A dynamically allocated pointer to the Tracked instance. The pointer would be set to nullptr by the pointed Tracked instance in the insance's destructor to mark the instance as expired. The same pointer instance is shared using std::shared_ptr with all objects requiring safe access to the Tracked instance.

#include &lt;iostream&gt;
#include &lt;memory&gt;

class Tracked
{
public:
    using Handle = std::shared_ptr&lt;Tracked*&gt;;
    Tracked() : handle_(new Tracked*(this)) { }
    ~Tracked() {*handle_ = nullptr;}
    void act() {std::cout &lt;&lt; "hello world!\n";}
    Handle getHandle() {return handle_;}
private:
    Handle handle_;
};

class Manager
{
public:
    void attach(Tracked &amp;tracked) {handle_ = tracked.getHandle();}
    void detach() {handle_.reset();}
    void invoke()
    {
        if(handle_ != nullptr)
        {
            if(*handle_ != nullptr)
                (*handle_)-&gt;act();
        }
    }
private:
    Tracked::Handle handle_;
};

int main()
{
    Manager a, b, c;
    {
        Tracked tracked;
        a.attach(tracked);
        b.attach(tracked);
        a.invoke(); //output: hello world!
    } //"tracked" goes out of scope: the handles in "a" and "b" are now invalidated.
    b.invoke();
    c.invoke();
}


I have found surprisingly little information on this, is this a known idiom or design pattern?

Edit:
At the conclusion of writing this question I realized that I could just allocate the Tracked object with new and manage the object with a std::shared_ptr, distributing a std::weak_ptr to each Manager. If std::weak_ptr::lock() would return a null shared_ptr, the Tracked instance would be expired.
I think using a bit of dynamic allocation std::shared_ptr and std::weak_ptr makes sense as they provide a solid implementation of the tracking behaviour you need.

Your original though has a nice property of not using any dynamic allocation.
If the tracking logic could be refine and made more general if might be a handy bit of library code to have around.

This is my attempt so far:

template &lt;typename T&gt;
class SafeRefTo;

template &lt;typename T&gt;
class Tracked : public T
{
public:
    using T::T;
    ~Tracked();
    void addReferee(SafeRefTo&lt;T&gt; *manager) {safeRefToThis = manager;}
    void markSafeRefInvalid() {safeRefToThis = nullptr;}
private:
    SafeRefTo&lt;T&gt; *safeRefToThis;
};

template &lt;typename T&gt;
class SafeRefTo
{
public:
    template &lt;typename... Args&gt;
    Tracked&lt;T&gt; makeTracked(Args... args)
    {
        Tracked&lt;T&gt; tracked{args...};
        attach(tracked);
        return tracked;
    }

    void attach(Tracked&lt;T&gt; &amp;tracked)
    {
        tracked_ = &amp;tracked;
        tracked_-&gt;addReferee(this);
    }
    void detach()
    {
        if(tracked_ != nullptr)
        {
            tracked_-&gt;markSafeRefInvalid();
            tracked_ = nullptr;
        }
    }
    template &lt;typename TrackedMemFun, typename... Args&gt;
    void invoke(TrackedMemFun fun, Args... args)
    {
        if(tracked_ != nullptr)
            (tracked_-&gt;*fun)(args...);
    }
private:
    Tracked&lt;T&gt; *tracked_;
};

template &lt;typename T&gt;
Tracked&lt;T&gt;::~Tracked()
{
    if(safeRefToThis != nullptr)
        safeRefToThis-&gt;detach();
}


Then the client code is simply:

#include &lt;iostream&gt;

class Actor
{
public:
    Actor() = default;
    Actor(std::string extraText)
    :
    extraText(extraText)
    {}

    void act(unsigned int times) {
        for(; times; --times)
        {
            std::cout &lt;&lt; "hello world!" &lt;&lt; extraText &lt;&lt; "\n";
        }
    }

private:
    std::string extraText;
};

int main()
{
    SafeRefTo&lt;Actor&gt; manager;
    {
        auto tracked(manager.makeTracked());
        manager.invoke(&amp;Actor::act, 1); //output: hello world!
    }//"tracked" goes out of scope: the pointer in "manager" is now invalidated.
    manager.invoke(&amp;Actor::act, 1);
}