Cbeam
Loading...
Searching...
No Matches
cbeam/lifecycle/singleton.hpp

Manages a single, shared resource of type T with controlled and explicit lifecycle management.

Manages a single, shared resource of type T with controlled and explicit lifecycle management.

Background and Motivation

In traditional singleton implementations, the singleton instance is often released at program termination by the runtime (via static object destruction). This can lead to issues if the singleton's destructor depends on resources that have already been destroyed earlier — for example, if other global or static objects that the singleton relies on have already been torn down.

By contrast, singleton and its base class singleton_control enable the creation and, most importantly, the explicit destruction of singleton objects without relying on the undefined order of static deinitialization. This ensures that resources can be released in a well-defined sequence at a consciously chosen point in time, which is particularly useful in scenarios with complex dependencies.

How It Works

Note on myResource.reset()

Depending on the use case, either use the std::shared_ptr interface, e.g. myResource.get().reset() (also see SingletonTest::ResourceRelease) or remove the singleton globally via singleton<T>::release(name).

// Create or retrieve the "Example" singleton of type MyClass
auto myResource = singleton<MyClass, int, std::string>::get("Example", 5, "Hello");
// We can get a std::shared_ptr from it directly
std::shared_ptr<MyClass> ptr = myResource; // Just another reference
// Release only our local pointer. The object remains alive as long as any shared_ptr references it.
ptr.reset();
// Explicitly remove the singleton from the global map if desired
singleton<MyClass>::release("Example");
// Or perform a full global destruction of all singletons:
singleton_control::reset();
Template Parameters
TThe resource type to manage.
ArgsConstructor parameter types for T.