Repository navigation
Expand file tree
/
Copy pathlocked_reference.hpp
More file actions
117 lines (100 loc) · 2.03 KB
/
Copy pathlocked_reference.hpp
File metadata and controls
117 lines (100 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#pragma once
#include "behaviortree_cpp/utils/safe_any.hpp"
#include <mutex>
namespace BT
{
/**
* @brief The LockedPtr class is used to share a pointer to an object
* and a mutex that protects the read/write access to that object.
*
* As long as the object remains in scope, the mutex is locked, therefore
* you must destroy this instance as soon as the pointer was used.
*
* LockedPtr does not own the object it points to: the owner is only expected
* to keep it alive while the mutex is locked. In particular, the pointer must
* not be considered valid after calling unlock().
*/
template <typename T>
class LockedPtr
{
public:
LockedPtr() = default;
LockedPtr(T* obj, std::mutex* obj_mutex) : ref_(obj), mutex_(obj_mutex)
{
mutex_->lock();
}
~LockedPtr()
{
if(mutex_ != nullptr)
{
mutex_->unlock();
}
}
LockedPtr(LockedPtr const&) = delete;
LockedPtr& operator=(LockedPtr const&) = delete;
LockedPtr(LockedPtr&& other) noexcept
{
std::swap(ref_, other.ref_);
std::swap(mutex_, other.mutex_);
}
LockedPtr& operator=(LockedPtr&& other) noexcept
{
std::swap(ref_, other.ref_);
std::swap(mutex_, other.mutex_);
return *this;
}
operator bool() const
{
return ref_ != nullptr;
}
void lock()
{
if(mutex_ != nullptr)
{
mutex_->lock();
}
}
void unlock()
{
if(mutex_ != nullptr)
{
mutex_->unlock();
}
}
const T* get() const
{
return ref_;
}
const T* operator->() const
{
return ref_;
}
T* operator->()
{
return ref_;
}
template <typename OtherT>
void assign(const OtherT& other)
{
if(ref_ == nullptr)
{
throw std::runtime_error("Empty LockedPtr reference");
}
else if constexpr(std::is_same_v<T, OtherT>)
{
*ref_ = other;
}
else if constexpr(std::is_same_v<BT::Any, OtherT>)
{
other->copyInto(*ref_);
}
else
{
*ref_ = T(other);
}
}
private:
T* ref_ = nullptr;
std::mutex* mutex_ = nullptr;
};
} // namespace BT