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 * SPDX-License-Identifier: MIT
13 ****************************************************************************/
14
15#ifndef CPL_AUTO_CLOSE_H_INCLUDED
16#define CPL_AUTO_CLOSE_H_INCLUDED
17
18#if defined(__cplusplus)
19#include <type_traits>
20
21/************************************************************************/
22/* CPLAutoClose */
23/************************************************************************/
24
33 template <typename _Ty, typename _Dx> class CPLAutoClose
34{
35 static_assert(!std::is_const<_Ty>::value && std::is_pointer<_Ty>::value,
36 "_Ty must is pointer type,_Dx must is function type");
37
38 private:
39 _Ty &m_ResourcePtr;
40 _Dx m_CloseFunc;
41
42 private:
43 CPLAutoClose(const CPLAutoClose &) = delete;
44 void operator=(const CPLAutoClose &) = delete;
45
46 public:
52 explicit CPLAutoClose(_Ty &ptr, _Dx dt)
53 : m_ResourcePtr(ptr), m_CloseFunc(dt)
54 {
55 }
56
60 ~CPLAutoClose()
61 {
62 if (m_ResourcePtr && m_CloseFunc)
63 m_CloseFunc(m_ResourcePtr);
64 }
65};
66
67#define CPL_AUTO_CLOSE_WARP(hObject, closeFunc) \
68 CPLAutoClose<decltype(hObject), decltype(closeFunc) *> \
69 tAutoClose##hObject(hObject, closeFunc)
70
71#endif /* __cplusplus */
72
73#endif /* CPL_AUTO_CLOSE_H_INCLUDED */
CPLAutoClose
The class use the destructor to automatically close the resource.
Definition cpl_auto_close.h:34
CPLAutoClose::CPLAutoClose
CPLAutoClose(_Ty &ptr, _Dx dt)
Constructor.
Definition cpl_auto_close.h:52
CPLAutoClose::~CPLAutoClose
~CPLAutoClose()
Destructor.
Definition cpl_auto_close.h:60