GDAL

cpl_auto_close.h
1/**********************************************************************
2 *
3 * Name: cpl_auto_close.h
4 * Project: CPL - Common Portability Library
5 * Purpose: CPL Auto Close handling
6 * Author: Liu Yimin, ymwh@foxmail.com
7 *
8 **********************************************************************
9 * Copyright (c) 2018, Liu Yimin
10 *
11 * SPDX-License-Identifier: MIT
12 ****************************************************************************/
13
14#ifndef CPL_AUTO_CLOSE_H_INCLUDED
15#define CPL_AUTO_CLOSE_H_INCLUDED
16
17#if defined(__cplusplus)
18#include <type_traits>
19
20/************************************************************************/
21/* CPLAutoClose */
22/************************************************************************/
23
32 template <typename _Ty, typename _Dx> class CPLAutoClose
33{
34 static_assert(!std::is_const<_Ty>::value && std::is_pointer<_Ty>::value,
35 "_Ty must is pointer type,_Dx must is function type");
36
37 private:
38 _Ty &m_ResourcePtr;
39 _Dx m_CloseFunc;
40
41 private:
42 CPLAutoClose(const CPLAutoClose &) = delete;
43 void operator=(const CPLAutoClose &) = delete;
44
45 public:
51 explicit CPLAutoClose(_Ty &ptr, _Dx dt)
52 : m_ResourcePtr(ptr), m_CloseFunc(dt)
53 {
54 }
55
59 ~CPLAutoClose()
60 {
61 if (m_ResourcePtr && m_CloseFunc)
62 m_CloseFunc(m_ResourcePtr);
63 }
64};
65
66#define CPL_AUTO_CLOSE_WARP(hObject, closeFunc) \
67 CPLAutoClose<decltype(hObject), decltype(closeFunc) *> \
68 tAutoClose##hObject(hObject, closeFunc)
69
70#endif /* __cplusplus */
71
72#endif /* CPL_AUTO_CLOSE_H_INCLUDED */
CPLAutoClose
The class use the destructor to automatically close the resource.
Definition cpl_auto_close.h:33
CPLAutoClose::CPLAutoClose
CPLAutoClose(_Ty &ptr, _Dx dt)
Constructor.
Definition cpl_auto_close.h:51
CPLAutoClose::~CPLAutoClose
~CPLAutoClose()
Destructor.
Definition cpl_auto_close.h:59