Line data Source code
1 : // SPDX-License-Identifier: Apache-2.0
2 : /**
3 : * Copyright (C) 2025 Samsung Electronics Co., Ltd. All Rights Reserved.
4 : *
5 : * @file singleton.h
6 : * @date 11 July 2025
7 : * @brief Base class making derived class singleton
8 : * @see https://github.com/nnstreamer/nntrainer
9 : * @author Grzegorz Kisala <g.kisala@samsung.com>
10 : * @bug No known bugs except for NYI items
11 : *
12 : */
13 :
14 : #ifndef __NNTRAINER_SINGLETON_H__
15 : #define __NNTRAINER_SINGLETON_H__
16 :
17 : #include <mutex>
18 :
19 : #include "noncopyable.h"
20 : #include "nonmovable.h"
21 :
22 : namespace nntrainer {
23 :
24 : /**
25 : * @class Singleton
26 : * @brief Use it as base class of singletons
27 : */
28 : template <typename T> class Singleton : public Noncopyable, public Nonmovable {
29 :
30 : public:
31 : /**
32 : * @brief Get reference to global instance object
33 : * once
34 : * @return Instance to singleton class reference
35 : */
36 11558 : static T &Global() {
37 11558 : static T instance;
38 : instance.initializeOnce();
39 11558 : return instance;
40 : }
41 :
42 : /**
43 : * @brief Initialize helper function ensuring that initialize is called only
44 : * once
45 : */
46 : void initializeOnce() {
47 11558 : std::call_once(initialized_, [&]() { this->initialize(); });
48 : }
49 :
50 : /**
51 : * @brief Default destructor
52 : */
53 57 : virtual ~Singleton() = default;
54 :
55 : protected:
56 : /**
57 : * @brief Default constructor
58 : */
59 : Singleton() = default;
60 :
61 : /**
62 : * @brief Override this function to initialize derived class
63 : */
64 2 : virtual void initialize() noexcept {}
65 :
66 : std::once_flag initialized_;
67 : };
68 :
69 : } // namespace nntrainer
70 :
71 : #endif // __NNTRAINER_SINGLETON_H__
|