C++ shared_singleton
You can use a static weak_ptr in the function to cache the shared instance without extending its lifetime:

template&lt;typename T&gt;
std::shared_ptr&lt;T&gt; get_shared_instance()
{
    static std::mutex m;
    static std::weak_ptr&lt;T&gt; cache;

    std::lock_guard&lt;std::mutex&gt; lg(m);

    std::shared_ptr&lt;T&gt; shared = cache.lock();
    if (cache.expired()) {
        shared.reset(new T);
        cache = shared;
    }
    return shared;
}


So, the first caller will find a default-initialized weak_ptr counts as expired, and construct a new T.

While the first caller is active (and keeping its new T alive), concurrent callers will get the same object, cached in the weak_ptr.  When the last concurrent user is done, the object will be destroyed.

A subsequent caller will find the weak_ptr expired (same as before the first call), and create a new T ... etc. etc.