SharedInstance.h
Go to the documentation of this file.
1 // This file is a part of the OpenSurgSim project.
2 // Copyright 2013, SimQuest Solutions Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #ifndef SURGSIM_FRAMEWORK_SHAREDINSTANCE_H
17 #define SURGSIM_FRAMEWORK_SHAREDINSTANCE_H
18 
19 #include <memory>
20 #include <functional>
21 
22 #include <boost/thread/mutex.hpp>
23 #include <boost/thread/locks.hpp>
24 
26 
27 
28 namespace SurgSim
29 {
30 namespace Framework
31 {
32 
35 
104 template <typename T>
106 {
107 public:
109  typedef std::function<std::shared_ptr<T>()> InstanceCreator;
110 
115  SharedInstance();
116 
120  explicit SharedInstance(const InstanceCreator& instanceCreator);
121 
123  ~SharedInstance();
124 
132  std::shared_ptr<T> get();
133 
134 private:
139 
142  std::shared_ptr<T> createInstance();
143 
150 
153 
155  std::weak_ptr<T> m_weakInstance;
156 
158  boost::mutex m_mutex;
159 };
160 
161 }; // namespace Framework
162 }; // namespace SurgSim
163 
165 
166 #endif // SURGSIM_FRAMEWORK_SHAREDINSTANCE_H
SharedInstance & operator=(const SharedInstance &)
Prevent assignment.
Definition: DriveElementFromInputBehavior.cpp:27
std::weak_ptr< T > m_weakInstance
A weak reference to the shared instance, if any.
Definition: SharedInstance.h:155
~SharedInstance()
Destroy the container and the data it contains.
Definition: SharedInstance-inl.h:46
boost::mutex m_mutex
Mutex for synchronization of object creation.
Definition: SharedInstance.h:158
static InstanceCreator defaultInstanceCreator()
Creates a function that can create an instance using std::make_shared<T>().
Definition: SharedInstance-inl.h:72
SharedInstance()
Create the SharedInstance object used to manage the shared instance.
Definition: SharedInstance-inl.h:34
InstanceCreator m_instanceCreator
A creator function used to construct the shared instance.
Definition: SharedInstance.h:152
The header that provides the assertion API.
std::function< std::shared_ptr< T >)> InstanceCreator
A type that can hold a function object or lambda that takes no arguments and returns std::shared_ptr<...
Definition: SharedInstance.h:109
A utility class to manage a shared instance of an object.
Definition: SharedInstance.h:105
std::shared_ptr< T > createInstance()
Creates an object instance.
Definition: SharedInstance-inl.h:64