BeeeOn Gateway  v2020.3.1-2-g6f737dc
Platform to interconnect the IoT world
AutoClose.h
1 #pragma once
2 
3 #include <Poco/Logger.h>
4 
5 #include "util/Loggable.h"
6 
7 namespace BeeeOn {
8 
9 template <typename Closable>
10 struct DefaultClose {
11  void operator() (Closable &c) const
12  {
13  c.close();
14  }
15 };
16 
17 template <typename Closable, typename Close = DefaultClose<Closable>>
18 class AutoClose : protected Loggable {
19 public:
20  AutoClose(Closable &c):
21  m_closable(c)
22  {
23  }
24 
29  AutoClose(const AutoClose &c) = delete;
30 
31  ~AutoClose()
32  {
33  try {
34  const Close close;
35  close(m_closable);
36 
37  if (logger().debug()) {
38  logger().debug(
39  "auto-close successful",
40  __FILE__, __LINE__
41  );
42  }
43  }
44  catch (...) {
45  logger().fatal(
46  "auto-close has failed",
47  __FILE__, __LINE__
48  );
49  }
50  }
51 
52  Closable *operator ->()
53  {
54  return &m_closable;
55  }
56 
57  const Closable *operator ->() const
58  {
59  return &m_closable;
60  }
61 
62  Closable &operator *()
63  {
64  return m_closable;
65  }
66 
67  const Closable &operator *() const
68  {
69  return m_closable;
70  }
71 
72 private:
73  Closable &m_closable;
74 };
75 
76 struct FdClose {
77  void operator() (const int fd) const;
78 };
79 
80 class FdAutoClose : public AutoClose<int, FdClose> {
81 public:
82  FdAutoClose(const int fd);
83 
84 private:
85  int m_fd;
86 };
87 
88 }
Definition: AutoClose.h:18
Definition: AutoClose.h:76
Definition: AutoClose.h:10
Definition: Loggable.h:19
Definition: AutoClose.h:80