uvw  2.12.1
resource.hpp
1 #ifndef UVW_RESOURCE_INCLUDE_H
2 #define UVW_RESOURCE_INCLUDE_H
3 
4 #include <memory>
5 #include <utility>
6 #include "emitter.h"
7 #include "underlying_type.hpp"
8 
9 namespace uvw {
10 
16 template<typename T, typename U>
17 class Resource: public UnderlyingType<T, U>, public Emitter<T>, public std::enable_shared_from_this<T> {
18 protected:
19  using ConstructorAccess = typename UnderlyingType<T, U>::ConstructorAccess;
20 
21  auto parent() const noexcept {
22  return this->loop().loop.get();
23  }
24 
25  void leak() noexcept {
26  sPtr = this->shared_from_this();
27  }
28 
29  void reset() noexcept {
30  sPtr.reset();
31  }
32 
33  bool self() const noexcept {
34  return static_cast<bool>(sPtr);
35  }
36 
37 public:
38  explicit Resource(ConstructorAccess ca, std::shared_ptr<Loop> ref)
39  : UnderlyingType<T, U>{ca, std::move(ref)} {
40  this->get()->data = this;
41  }
42 
47  template<typename R = void>
48  std::shared_ptr<R> data() const {
49  return std::static_pointer_cast<R>(userData);
50  }
51 
56  void data(std::shared_ptr<void> uData) {
57  userData = std::move(uData);
58  }
59 
60 private:
61  std::shared_ptr<void> userData{nullptr};
62  std::shared_ptr<void> sPtr{nullptr};
63 };
64 
65 } // namespace uvw
66 
67 #endif // UVW_RESOURCE_INCLUDE_H
Event emitter base class.
Definition: emitter.h:82
Common class for almost all the resources available in uvw.
Definition: resource.hpp:17
std::shared_ptr< R > data() const
Gets user-defined data. uvw won't use this field in any case.
Definition: resource.hpp:48
void data(std::shared_ptr< void > uData)
Sets arbitrary data. uvw won't use this field in any case.
Definition: resource.hpp:56
Wrapper class for underlying types.
Loop & loop() const noexcept
Gets the loop from which the resource was originated.
uvw default namespace.
Definition: async.h:8