cgv
Loading...
Searching...
No Matches
ref_arr.h
1#pragma once
2
3#include <cgv/defines/assert.h>
4#include <cgv/type/cond/is_base_of.h>
5#include <cgv/type/cond/has_virtual_destructor.h>
6
7namespace cgv {
9 namespace data {
10
11template <typename T>
13{
14private:
16 struct counter_type
17 {
18 counter_type(T* a, int c) : arr(a), count(c) {}
19 T* arr;
20 int count;
21 };
23 counter_type* counter;
25 T* arr;
27 void release()
28 {
29 if (counter) {
30 if (--counter->count == 0) {
31 delete [] counter->arr;
32 delete counter;
33 }
34 counter = 0;
35 }
36 arr = 0;
37 }
38public:
40 explicit ref_arr(T* a = 0, counter_type* c = 0) : counter(c), arr(a) {
41 if (!c && a)
42 counter = new counter_type(a, 1);
43 }
45 ref_arr(const ref_arr<T>& ra) : counter(ra.counter), arr(ra.arr)
46 {
47 if (counter)
48 ++counter->count;
49 }
52 release();
53 }
56 if (this == &ra)
57 return *this;
58 release();
59 new (this) ref_arr<T>(ra);
60 return *this;
61 }
63 T* ptr() const {
64 return arr;
65 }
67 T& operator*() const {
68 return *arr;
69 }
71 T* operator->() const {
72 return arr;
73 }
75 T& operator [] (int i) {
76 return arr[i];
77 }
79 ref_arr<T> operator () (int i) const {
80 return ref_arr<T>(arr+i,counter);
81 }
83 bool operator == (const ref_arr<T>& ra) const {
84 return arr == ra.arr;
85 }
87 int get_count() const {
88 return counter ? counter->count : 0;
89 }
91 bool unique() const {
92 return get_count() <= 1;
93 }
95 bool empty() const {
96 return get_count() == 0;
97 }
99 operator bool () const {
100 return !empty();
101 }
103 void clear() {
104 release();
105 }
106};
107
108 }
109}
T & operator[](int i)
access to i-th element
Definition ref_arr.h:75
ref_arr(const ref_arr< T > &ra)
copy construct from same pointer type and increment count
Definition ref_arr.h:45
T * operator->() const
access to element pointer
Definition ref_arr.h:71
void clear()
clear the array pointer
Definition ref_arr.h:103
bool unique() const
check if this is the only reference
Definition ref_arr.h:91
~ref_arr()
destruct reference counted pointer
Definition ref_arr.h:51
int get_count() const
return current count
Definition ref_arr.h:87
bool empty() const
check if pointer is not yet set
Definition ref_arr.h:95
ref_arr< T > operator()(int i) const
return an array pointer pointing to the i-th element
Definition ref_arr.h:79
ref_arr< T > & operator=(const ref_arr< T > &ra)
assignment to pointer of same type
Definition ref_arr.h:55
bool operator==(const ref_arr< T > &ra) const
compare by pointer
Definition ref_arr.h:83
T & operator*() const
access to element
Definition ref_arr.h:67
ref_arr(T *a=0, counter_type *c=0)
construct reference counted pointer
Definition ref_arr.h:40
T * ptr() const
return array pointer
Definition ref_arr.h:63
the cgv namespace
Definition print.h:11