| 15 | */ |
| 16 | template <typename T> |
| 17 | class LockedPtr |
| 18 | { |
| 19 | public: |
| 20 | LockedPtr() = default; |
| 21 | |
| 22 | LockedPtr(T* obj, std::mutex* obj_mutex) : ref_(obj), mutex_(obj_mutex) |
| 23 | { |
| 24 | mutex_->lock(); |
| 25 | } |
| 26 | |
| 27 | ~LockedPtr() |
| 28 | { |
| 29 | if(mutex_ != nullptr) |
| 30 | { |
| 31 | mutex_->unlock(); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | LockedPtr(LockedPtr const&) = delete; |
| 36 | LockedPtr& operator=(LockedPtr const&) = delete; |
| 37 | |
| 38 | LockedPtr(LockedPtr&& other) noexcept |
| 39 | { |
| 40 | std::swap(ref_, other.ref_); |
| 41 | std::swap(mutex_, other.mutex_); |
| 42 | } |
| 43 | |
| 44 | LockedPtr& operator=(LockedPtr&& other) noexcept |
| 45 | { |
| 46 | std::swap(ref_, other.ref_); |
| 47 | std::swap(mutex_, other.mutex_); |
| 48 | return *this; |
| 49 | } |
| 50 | |
| 51 | operator bool() const |
| 52 | { |
| 53 | return ref_ != nullptr; |
| 54 | } |
| 55 | |
| 56 | void lock() |
| 57 | { |
| 58 | if(mutex_ != nullptr) |
| 59 | { |
| 60 | mutex_->lock(); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | void unlock() |
| 65 | { |
| 66 | if(mutex_ != nullptr) |
| 67 | { |
| 68 | mutex_->unlock(); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | const T* get() const |
| 73 | { |
| 74 | return ref_; |