Easy way to share data between instances

Sometimes you need to share data between instances, but you need that data to be accessed externally, automatically created when needed, and destroyed when not needed anymore.

You can use something like this:

template<typename T>
std::shared_ptr<T> getSharedData()
    static std::mutex mtx;
    static std::weak_ptr<T> ptr;
    std::lock_guard<std::mutex> lk(mtx);
    auto p = ptr.lock();
    if (p)
        return p;
    p = std::make_shared<T>();
    ptr = p;
    return p;

This way you can have instances getting a strong reference to that data, creating it if necessary.

struct FooSharedData 
    // ... details here

class Foo
    Foo() : m_shared(getSharedData<FooSharedData>()) { }
    std::shared_ptr<FooSharedData> m_shared;

void someFunction()
        Foo a; // Will create the FooSharedData instance
        Foo b; // Will grab the existing FooSharedData instance
        // Can access it externally too
        auto data = getSharedData<FooSharedData>();
    // At this point, there are no more strong references to the FooSharedData instance,
    // so it gets deleted

    // This will recreate a FooSharedData instance, since the previous one was destroyed
    Foo c;


The source code in this article is licensed under the CC0 license, so feel free to copy, modify, share, do whatever you want with it.
No attribution is required, but I’ll be happy if you do.

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x