add:添加一个单例生成类。

This commit is contained in:
taynpg 2024-12-07 22:31:27 +08:00
parent 0b760f5363
commit 7f5d41812d
3 changed files with 33 additions and 1 deletions

View File

@ -14,7 +14,7 @@ message(STATUS "Compiler CXX ID: ${CMAKE_CXX_COMPILER_ID}")
set(SRC_FILES
src/of_path.cpp src/of_str.cpp
src/of_win.cpp
src/of_win.cpp src/of_util.cpp
)
include_directories(include)

31
include/of_util.h Normal file
View File

@ -0,0 +1,31 @@
#include "of_def.hpp"
#include <cassert>
#include <iostream>
#include <memory>
#include <mutex>
namespace ofen {
template <typename T> class OfSingleton
{
public:
OfSingleton(const OfSingleton&) = delete;
OfSingleton& operator=(const OfSingleton&) = delete;
static std::shared_ptr<T> getInstance()
{
std::call_once(init_flag, []() { instance.reset(new T()); });
return instance;
}
protected:
OfSingleton() = default;
virtual ~OfSingleton() = default;
private:
static std::shared_ptr<T> instance;
static std::once_flag init_flag;
};
template <typename T> std::shared_ptr<T> OfSingleton<T>::instance = nullptr;
template <typename T> std::once_flag OfSingleton<T>::init_flag;
} // namespace ofen

1
src/of_util.cpp Normal file
View File

@ -0,0 +1 @@
#include "of_util.h"