I created a little singleton
-like class that gets deleted when there is no reference to it anymore (so its lifetime shall be somewhat predictable). I aimed to make it thread-safe.
#include <memory>
#include <mutex>
template< typename t_type >
struct shared_instance
{
static std::shared_ptr< t_type > get_shared_instance()
{
static std::weak_ptr< t_type > weak;
static std::mutex mutex;
auto result = weak.lock();
if( nullptr == result )
{
std::unique_lock< std::mutex > lock{ mutex };
result = weak.lock();
if( nullptr != result )
{
return result;
}
result = std::make_shared< t_type >();
weak = result;
}
return result;
}
};
template< typename t >
struct context
{
context()
: instance{ shared_instance< t >::get_shared_instance() }
{ }
private: std::shared_ptr< t > instance;
};
I would be glad if you could comment on the implementation itself and how I could tackle non-default-constructible objects (I know of perfect forwarding and variadic templates but I have not found an elegant way to evaluate them lazily).
context c1{}; /*some code here*/; context c2{};
c2 will tear down the context but it c1 should (braoder scope, calling the create-function mutliple times is not an error from the c-library's point of view). i need a way to make sure that behind the scenes there is only one call to destroy in the dtor of the last instance \$\endgroup\$