forked from kirillkovalenko/nssm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_ptr.h
More file actions
99 lines (84 loc) · 2.46 KB
/
Copy pathheap_ptr.h
File metadata and controls
99 lines (84 loc) · 2.46 KB
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
#ifndef HEAP_PTR_H
#define HEAP_PTR_H
/*
Heap memory management policies for the smart_ptr library,
and a scoped heap buffer class for temporary allocations.
heap_mem_mgr<T> - for shared_ptr to manage HeapAlloc'd objects
heap_array_mgr<T> - for shared_array to manage HeapAlloc'd buffers
ScopedHeapBuffer<T> - RAII wrapper for local HeapAlloc'd buffers
*/
#include <windows.h>
#include <string>
/* Securely clear a wstring's contents from memory before deallocation. */
inline void secure_clear(std::wstring& s) {
if (!s.empty())
{
SecureZeroMemory(&s[0], s.size() * sizeof(wchar_t));
}
s.clear();
}
/* Memory manager policy that uses HeapAlloc/HeapFree. */
namespace smart_ptr {
template <typename T>
class heap_mem_mgr {
public:
static void deallocate(T* p) {
if (p) HeapFree(GetProcessHeap(), 0, p);
}
static T* allocate() {
return static_cast<T*>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(T)));
}
};
template <typename T>
class heap_array_mgr {
public:
static void deallocate(T* p) {
if (p) HeapFree(GetProcessHeap(), 0, p);
}
};
} // namespace smart_ptr
/*
ScopedHeapBuffer: non-copyable RAII wrapper for a HeapAlloc'd buffer.
Use for the common pattern of local TCHAR* buf = HeapAlloc(...);
The destructor calls HeapFree automatically.
*/
template <typename T>
class ScopedHeapBuffer {
public:
ScopedHeapBuffer() : ptr_(NULL) {}
explicit ScopedHeapBuffer(size_t count) {
ptr_ = static_cast<T*>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, count * sizeof(T)));
}
~ScopedHeapBuffer() {
if (ptr_) HeapFree(GetProcessHeap(), 0, ptr_);
}
/* Allocate (or reallocate) the buffer. Returns false on failure. */
bool alloc(size_t count) {
if (ptr_)
{
HeapFree(GetProcessHeap(), 0, ptr_);
ptr_ = NULL;
}
ptr_ = static_cast<T*>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, count * sizeof(T)));
return ptr_ != NULL;
}
T* get() const { return ptr_; }
T& operator[](size_t i) { return ptr_[i]; }
const T& operator[](size_t i) const { return ptr_[i]; }
T& operator[](int i) { return ptr_[i]; }
const T& operator[](int i) const { return ptr_[i]; }
operator T* () const { return ptr_; }
operator bool() const { return ptr_ != NULL; }
bool operator!() const { return ptr_ == NULL; }
/* Release ownership without freeing. */
T* detach() {
T* p = ptr_;
ptr_ = NULL;
return p;
}
private:
T* ptr_;
ScopedHeapBuffer(const ScopedHeapBuffer&);
ScopedHeapBuffer& operator=(const ScopedHeapBuffer&);
};
#endif