-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRefCntMem.cpp
More file actions
108 lines (97 loc) · 2.37 KB
/
RefCntMem.cpp
File metadata and controls
108 lines (97 loc) · 2.37 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
100
101
102
103
104
105
106
107
108
///////////////////////////////////////////////////////////////////////////
//
// NAME
// RefCntMem.cpp -- reference-counted heap memory
//
// SEE ALSO
// RefCntMem.h definition and explanation of this class
//
// Copyright © Richard Szeliski, 2001.
// See Copyright.h for more details
//
///////////////////////////////////////////////////////////////////////////
#include "RefCntMem.h"
CRefCntMem::CRefCntMem()
{
// Default constructor
m_ptr = 0;
}
CRefCntMem::~CRefCntMem()
{
// Destructor
DecrementCount();
m_ptr = 0; // not necessary, just for debugging
}
void CRefCntMem::DecrementCount()
{
// Decrement the reference count and delete if done
if (m_ptr)
{
m_ptr->m_refCnt -= 1;
if (m_ptr->m_refCnt == 0)
{
if (m_ptr->m_deleteWhenDone)
{
if (m_ptr->m_delFn)
m_ptr->m_delFn(m_ptr->m_memory);
else
delete (double *) m_ptr->m_memory;
}
delete m_ptr;
}
}
}
void CRefCntMem::IncrementCount()
{
// Increment the reference count
if (m_ptr)
{
m_ptr->m_refCnt += 1;
}
}
CRefCntMem::CRefCntMem(const CRefCntMem& ref)
{
// Copy constructor
m_ptr = 0;
(*this) = ref; // use assignment operator
}
CRefCntMem& CRefCntMem::operator=(const CRefCntMem& ref)
{
// Assignment
DecrementCount(); // if m_ptr exists, no longer pointing to it
m_ptr = ref.m_ptr;
IncrementCount();
return *this;
}
void CRefCntMem::ReAllocate(int nBytes, void *memory, bool deleteWhenDone,
void (*deleteFunction)(void *ptr))
{
// Allocate/deallocate memory
DecrementCount();
if (memory)
{
m_ptr = new CRefCntMemPtr;
m_ptr->m_nBytes = nBytes;
m_ptr->m_memory = memory;
m_ptr->m_deleteWhenDone = deleteWhenDone;
m_ptr->m_refCnt = 1;
m_ptr->m_delFn = deleteFunction;
}
else
m_ptr = 0; // don't bother storing pointer to null memory
}
int CRefCntMem::NBytes()
{
// Number of stored bytes
return (m_ptr) ? m_ptr->m_nBytes : 0;
}
bool CRefCntMem::InBounds(int index)
{
// Check if index is in bounds
return (m_ptr && 0 <= index && index < m_ptr->m_nBytes);
}
void* CRefCntMem::Memory()
{
// Pointer to allocated memory
return (m_ptr) ? m_ptr->m_memory : 0;
}