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