All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
staticData.h
Go to the documentation of this file.
1//
2// Copyright 2016 Pixar
3//
4// Licensed under the terms set forth in the LICENSE.txt file available at
5// https://openusd.org/license.
6//
7#ifndef PXR_BASE_TF_STATIC_DATA_H
8#define PXR_BASE_TF_STATIC_DATA_H
9
12
13#include "pxr/pxr.h"
14#include "pxr/base/arch/hints.h"
15#include "pxr/base/tf/preprocessorUtilsLite.h"
16
17#include <atomic>
18#include <type_traits>
19
20PXR_NAMESPACE_OPEN_SCOPE
21
90template <class T>
91struct Tf_StaticDataDefaultFactory {
92 static T *New() { return new T; }
93};
94
95template <class T, class Factory = Tf_StaticDataDefaultFactory<T> >
97public:
100 inline T* operator-> () const { return Get(); }
101
104 inline T& operator* () const { return *Get(); }
105
108 inline T* Get() const {
109 T *p = _data;
110 return ARCH_LIKELY(p) ? p : _TryToCreateData();
111 }
112
115 inline bool IsInitialized() const { return _data.load() != nullptr; }
116
117private:
118 T *_TryToCreateData() const {
119 // Allocate an instance.
120 T *tmp = Factory::New();
121
122 // Try to atomically set the pointer from null to tmp.
123 T *n = nullptr;
124 if (ARCH_LIKELY(_data.compare_exchange_strong(n, tmp)))
125 return tmp;
126
127 // Another thread won the initialization race.
128 delete tmp;
129 return _data;
130 }
131
132 mutable std::atomic<T *> _data;
133};
134
181#define TF_MAKE_STATIC_DATA(Type, Name) \
182 static void TF_PP_CAT(Name,_Tf_StaticDataFactoryImpl)( \
183 std::remove_const_t<TF_PP_EAT_PARENS(Type)> *); \
184 namespace { \
185 struct TF_PP_CAT(Name,_Tf_StaticDataFactory) { \
186 static TF_PP_EAT_PARENS(Type) *New() { \
187 auto *p = new std::remove_const_t<TF_PP_EAT_PARENS(Type)>; \
188 TF_PP_CAT(Name,_Tf_StaticDataFactoryImpl)(p); \
189 return p; \
190 } \
191 }; \
192 } \
193 static TfStaticData< \
194 TF_PP_EAT_PARENS(Type), TF_PP_CAT(Name,_Tf_StaticDataFactory)> Name; \
195 static void TF_PP_CAT(Name,_Tf_StaticDataFactoryImpl)( \
196 std::remove_const_t<TF_PP_EAT_PARENS(Type)> *Name)
197
198PXR_NAMESPACE_CLOSE_SCOPE
199
200#endif
Create or return a previously created object instance of global data.
Definition: staticData.h:96
T & operator*() const
Member lookup.
Definition: staticData.h:104
bool IsInitialized() const
Return true if the underlying data object is created and initialized.
Definition: staticData.h:115
T * operator->() const
Return a pointer to the underlying data object.
Definition: staticData.h:100
T * Get() const
Return a pointer to the underlying object, creating and initializing it if necessary.
Definition: staticData.h:108
Compiler hints.