35 lines
888 B
C++
35 lines
888 B
C++
// AUTOGENERATED COPYRIGHT HEADER START
|
|
// Copyright (C) 2023 Michael Fabian 'Xaymar' Dirks <info@xaymar.com>
|
|
// AUTOGENERATED COPYRIGHT HEADER END
|
|
|
|
#pragma once
|
|
#include "warning-disable.hpp"
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include "warning-enable.hpp"
|
|
|
|
namespace streamfx::util {
|
|
/** Reference counted Singleton implementation
|
|
*
|
|
* Call _classname::instance() to get a reference, which will self-delete when not referenced anymore.
|
|
*
|
|
*/
|
|
template<class _type>
|
|
class singleton : public std::enable_shared_from_this<_type> {
|
|
public:
|
|
static std::shared_ptr<_type> instance()
|
|
{
|
|
static std::weak_ptr<_type> winst;
|
|
static std::mutex mtx;
|
|
std::unique_lock<decltype(mtx)> lock(mtx);
|
|
|
|
auto ptr = winst.lock();
|
|
if (!ptr) {
|
|
ptr = std::shared_ptr<_type>(new _type());
|
|
winst = ptr;
|
|
}
|
|
return ptr;
|
|
}
|
|
};
|
|
} // namespace streamfx::util
|