]> git.cworth.org Git - apitrace/blob - thirdparty/directxtex/DirectXTex/scoped.h
directxtex: Get it building on MinGW.
[apitrace] / thirdparty / directxtex / DirectXTex / scoped.h
1 //-------------------------------------------------------------------------------------
2 // scoped.h
3 //  
4 // Utility header with helper classes for exception-safe handling of resources
5 //
6 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
7 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
8 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
9 // PARTICULAR PURPOSE.
10 //
11 // Copyright (c) Microsoft Corporation. All rights reserved.
12 //-------------------------------------------------------------------------------------
13
14 #if defined(_MSC_VER) && (_MSC_VER > 1000)
15 #pragma once
16 #endif
17
18 #include <assert.h>
19 #include <memory>
20 #include <malloc.h>
21
22 //---------------------------------------------------------------------------------
23 struct aligned_deleter { void operator()(void* p) { _aligned_free(p); } };
24
25 typedef std::unique_ptr<float, aligned_deleter> ScopedAlignedArrayFloat;
26
27 #ifdef USE_XNAMATH
28 typedef std::unique_ptr<XMVECTOR, aligned_deleter> ScopedAlignedArrayXMVECTOR;
29 #else
30 typedef std::unique_ptr<DirectX::XMVECTOR, aligned_deleter> ScopedAlignedArrayXMVECTOR;
31 #endif
32
33 //---------------------------------------------------------------------------------
34 struct handle_closer { void operator()(HANDLE h) { assert(h != INVALID_HANDLE_VALUE); if (h) CloseHandle(h); } };
35
36 typedef std::unique_ptr<void, handle_closer> ScopedHandle;
37
38 inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? 0 : h; }
39
40
41 //---------------------------------------------------------------------------------
42 template<class T> class ScopedObject
43 {
44 public:
45     explicit ScopedObject( T *p = 0 ) : _pointer(p) {}
46     ~ScopedObject()
47     {
48         if ( _pointer )
49         {
50             _pointer->Release();
51             _pointer = nullptr;
52         }
53     }
54
55     bool IsNull() const { return (!_pointer); }
56
57     T& operator*() { return *_pointer; }
58     T* operator->() { return _pointer; }
59     T** operator&() { return &_pointer; }
60
61     void Reset(T *p = 0) { if ( _pointer ) { _pointer->Release(); } _pointer = p; }
62
63     T* Get() const { return _pointer; }
64
65 private:
66     ScopedObject(const ScopedObject&);
67     ScopedObject& operator=(const ScopedObject&);
68         
69     T* _pointer;
70 };