forked from cjlin1/liblinear
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_buffer.h
More file actions
78 lines (63 loc) · 1.62 KB
/
memory_buffer.h
File metadata and controls
78 lines (63 loc) · 1.62 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
#ifndef _MEMORY_BUFFER
#define _MEMORY_BUFFER
#include <assert.h>
// Simple memory buffer for RAII
template<typename TItemType>
class CBuffer {
public:
CBuffer() : count( 0 ), ptr( 0 ) {}
explicit CBuffer( size_t count );
~CBuffer();
size_t Count() const { return count; }
TItemType* Detach();
void Realloc( size_t new_size );
TItemType& operator[]( int index ) { assert( ptr != 0 ); return ptr[index]; }
TItemType* operator->() { assert( count == 1 ); return ptr; }
operator TItemType*() { return ptr; } // bad idea, but less code changed
// Better way, may be in future
TItemType* Ptr() { assert( ptr != 0 ); return ptr; }
private:
size_t count;
TItemType* ptr;
// prohibited
CBuffer( const CBuffer<TItemType>& other );
const CBuffer<TItemType>& operator=( const CBuffer<TItemType>& other );
};
// ----------------------------------------------------------------------------
template<typename TItemType>
inline CBuffer<TItemType>::CBuffer( size_t _count ) :
count( _count ),
ptr( 0 )
{
assert( count > 0 );
ptr = new TItemType[count];
}
template<typename TItemType>
inline CBuffer<TItemType>::~CBuffer()
{
if( ptr != 0 ) {
delete[] ptr;
ptr = 0;
}
}
template<typename TItemType>
inline TItemType* CBuffer<TItemType>::Detach()
{
TItemType* tmp = ptr;
ptr = 0;
count = 0;
return tmp;
}
template<typename TItemType>
inline void CBuffer<TItemType>::Realloc( size_t new_count )
{
assert( new_count > count );
TItemType* buffer = new TItemType[new_count];
if( count > 0 ) {
::memcpy( buffer, ptr, count * sizeof( TItemType ) );
delete[] Detach();
}
ptr = buffer;
count = new_count;
}
#endif // _MEMORY_BUFFER