GDAL
cpl_auto_close.h
1 /**********************************************************************
2  * $Id$
3  *
4  * Name: cpl_auto_close.h
5  * Project: CPL - Common Portability Library
6  * Purpose: CPL Auto Close handling
7  * Author: Liu Yimin, ymwh@foxmail.com
8  *
9  **********************************************************************
10  * Copyright (c) 2018, Liu Yimin
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a
13  * copy of this software and associated documentation files (the "Software"),
14  * to deal in the Software without restriction, including without limitation
15  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
16  * and/or sell copies of the Software, and to permit persons to whom the
17  * Software is furnished to do so, subject to the following conditions:
18  *
19  * The above copyright notice and this permission notice shall be included
20  * in all copies or substantial portions of the Software.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28  * DEALINGS IN THE SOFTWARE.
29  ****************************************************************************/
30 
31 #ifndef CPL_AUTO_CLOSE_H_INCLUDED
32 #define CPL_AUTO_CLOSE_H_INCLUDED
33 
34 #if defined(__cplusplus)
35 #include <type_traits>
36 
37 /************************************************************************/
38 /* CPLAutoClose */
39 /************************************************************************/
40 
49 template <typename _Ty, typename _Dx> class CPLAutoClose
50 {
51  static_assert(!std::is_const<_Ty>::value && std::is_pointer<_Ty>::value,
52  "_Ty must is pointer type,_Dx must is function type");
53 
54  private:
55  _Ty &m_ResourcePtr;
56  _Dx m_CloseFunc;
57 
58  private:
59  CPLAutoClose(const CPLAutoClose &) = delete;
60  void operator=(const CPLAutoClose &) = delete;
61 
62  public:
68  explicit CPLAutoClose(_Ty &ptr, _Dx dt)
69  : m_ResourcePtr(ptr), m_CloseFunc(dt)
70  {
71  }
72 
77  {
78  if (m_ResourcePtr && m_CloseFunc)
79  m_CloseFunc(m_ResourcePtr);
80  }
81 };
82 
83 #define CPL_AUTO_CLOSE_WARP(hObject, closeFunc) \
84  CPLAutoClose<decltype(hObject), decltype(closeFunc) *> \
85  tAutoClose##hObject(hObject, closeFunc)
86 
87 #endif /* __cplusplus */
88 
89 #endif /* CPL_AUTO_CLOSE_H_INCLUDED */
The class use the destructor to automatically close the resource.
Definition: cpl_auto_close.h:50
CPLAutoClose(_Ty &ptr, _Dx dt)
Constructor.
Definition: cpl_auto_close.h:68
~CPLAutoClose()
Destructor.
Definition: cpl_auto_close.h:76