summaryrefslogtreecommitdiffstats
path: root/xbmc/utils/ScopeGuard.h
blob: 2f731fbeb38e61d1b4c4d47cf401866aac186dfc (plain)
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
/*
 *  Copyright (C) 2005-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#pragma once

#include <functional>

namespace KODI
{
namespace UTILS
{

/*! \class CScopeGuard
    \brief Generic scopeguard designed to handle any type of handle

    This is not necessary but recommended to cut down on some typing
    using CSocketHandle = CScopeGuard<SOCKET, INVALID_SOCKET, closesocket>;

    CSocketHandle sh(closesocket, open(thingy));
 */
template<typename Handle, Handle invalid, typename Deleter>
class CScopeGuard
{

public:

  CScopeGuard(std::function<Deleter> del, Handle handle = invalid)
    : m_handle{handle}
    , m_deleter{del}
  { };

  ~CScopeGuard() noexcept
  {
    reset();
  }

  operator Handle() const
  {
    return m_handle;
  }

  operator bool() const
  {
    return m_handle != invalid;
  }

  /*! \brief  attach a new handle to this instance, if there's
              already a handle it will be closed.

      \param[in]  handle  The handle to manage
   */
  void attach(Handle handle)
  {
    reset();

    m_handle = handle;
  }

  /*! \brief release the managed handle so that it won't be auto closed

      \return The handle being managed by the guard
   */
  Handle release()
  {
    Handle h = m_handle;
    m_handle = invalid;
    return h;
  }

  /*! \brief reset the instance, closing any managed handle and setting it to invalid
   */
  void reset()
  {
    if (m_handle != invalid)
    {
      m_deleter(m_handle);
      m_handle = invalid;
    }
  }

  //Disallow default construction and copying
  CScopeGuard() = delete;
  CScopeGuard(const CScopeGuard& rhs) = delete;
  CScopeGuard& operator= (const CScopeGuard& rhs) = delete;

  //Allow moving
  CScopeGuard(CScopeGuard&& rhs) noexcept
    : m_handle{std::move(rhs.m_handle)}, m_deleter{std::move(rhs.m_deleter)}
  {
    // Bring moved-from object into released state so destructor will not do anything
    rhs.release();
  }
  CScopeGuard& operator=(CScopeGuard&& rhs) noexcept
  {
    attach(rhs.release());
    m_deleter = std::move(rhs.m_deleter);
    return *this;
  }

private:
  Handle m_handle;
  std::function<Deleter> m_deleter;
};

}
}