-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsafe-buffer.hpp
65 lines (57 loc) · 1.52 KB
/
safe-buffer.hpp
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
#ifndef SAFE_BUFFER_HPP___
#define SAFE_BUFFER_HPP___
#include <algorithm>
#include <cstring>
template <class T>
class SafeBuffer {
public:
// Constructors
// --------------------------------------------------------
SafeBuffer() : mData() {
mData = (T *)0;
mSize = 0;
}
SafeBuffer(unsigned int size) : mSize(size) {
mData = (mSize) ? new T[mSize] : (T *)0;
}
// Destructors
// ---------------------------------------------------------
virtual ~SafeBuffer() {
if (mData) {
delete[] mData;
}
}
// Copy Constructor
// ---------------------------------------------------------
SafeBuffer(const SafeBuffer<T> &x) : mSize(x.mSize) {
if (mSize != 0) {
mData = new T[mSize];
std::memcpy(mData, x.mData, mSize);
} else {
mData = (T *)0;
}
}
// Move constructor
// ---------------------------------------------------------
SafeBuffer(SafeBuffer<T> &&x) {
mData = x.mData;
x.mData = (T *)0;
}
// Assignment
// If the assignment is called with a lvalue the copy constructor will be
// called
// If the assignment is called with a rvalue the move constructire will be
// called
// ---------------------------------------------------------
SafeBuffer<T> &operator=(const SafeBuffer<T> x) {
std::swap(mSize, x.mSize);
std::swap(mData, x.mData);
return *this;
}
const T &operator[](const uint32_t pos) { return mData[pos]; }
T &&operator[](const uint32_t pos) { return mData[pos]; }
private:
T *mData;
uint32_t mSize;
};
#endif