#include <ObjectsRegistry.hpp>
Public Member Functions | |
template<typename CreateObjectType> | |
StrongPtrType | Get (const KeyType &Key, CreateObjectType &&CreateObject) noexcept(false) |
StrongPtrType | Get (const KeyType &Key) |
void | Purge () |
Removes all expired pointers from the cache. | |
template<typename HandlerType> | |
void | ProcessElements (HandlerType &&Handler) |
Processes each element in the cache with the specified handler. | |
void | Clear () |
Removes all objects from the cache. | |
A thread-safe and exception-safe object registry that works with std::shared_ptr or RefCntAutoPtr. The registry keeps weak pointers to the objects and returns strong pointers if the requested object exits. An application should keep strong pointers to the objects to keep them alive.
Usage example for RefCntAutoPtr:
ObjectsRegistry<std::string, RefCntAutoPtr<IObject>> Registry; auto pObj = Registry.Get("Key", []() { RefCntAutoPtr<IObject> pObj; // Create object return pObj; });
Usage example for shared_ptr:
struct RegistryData { // ... }; ObjectsRegistry<std::string, std::shared_ptr<RegistryData>> Registry; auto pObj = Registry.Get("Key", []() { return std::make_shared<RegistryData>(); });
If the object is not found in the registry, it is atomically created by the provided initializer function. If the object is found, the initializer function is not called.
It is guaranteed, that the Object will only be initialized once, even if multiple threads call Get() simultaneously.
|
inline |
Finds the object in the registry and returns a strong pointer to it (std::shared_ptr or RefCntAutoPtr). If the object is not found, returns empty pointer.
[in] | Key | - The object key. |
Strong pointer to the object with the specified key, if the object is found in the registry, or empty pointer otherwise.
|
inline |
Finds the object in the registry and returns strong pointer to it (std::shared_ptr or RefCntAutoPtr). If the object is not found, it is atomically created using the provided initializer.
[in] | Key | - The object key. |
[in] | CreateObject | - Initializer function that is called if the object is not found in the registry. |
CreateObject function may throw in case of an error.
It is guaranteed, that the Object will only be initialized once, even if multiple threads call Get() simultaneously. However, if another thread runs an overloaded Get() without the initializer function with the same key, it may remove the entry from the registry, and the object will be initialized multiple times. This is OK as only one object will be added to the registry.