libsidplayfp  0.3.5
array.h
1 /*
2  * Copyright (C) 2011 Leandro Nini
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18 
19 #ifndef ARRAY_H
20 #define ARRAY_H
21 
22 class counter {
23 
24 private:
25  unsigned int c;
26 
27 public:
28  counter() : c(1) {}
29  void increase() { ++c; }
30  unsigned int decrease() { return --c; }
31 };
32 
35 template<typename T>
36 class array {
37 
38 private:
39  counter* count;
40  unsigned int x, y;
41  T* data;
42 
43 public:
44  array(const unsigned int x, const unsigned int y) :
45  count(new counter()),
46  x(x),
47  y(y),
48  data(new T[x * y]) {}
49 
50  array(const array& p) :
51  count(p.count),
52  x(p.x),
53  y(p.y),
54  data(p.data) { count->increase(); }
55 
56  ~array() { if (count->decrease() == 0) { delete count; delete [] data; } }
57 
58  unsigned int length() const { return x * y; }
59 
60  T* operator[](unsigned int a) { return a<x ? &data[a * y] : 0; }
61 
62  T const* operator[](unsigned int a) const { return a<x ? &data[a * y] : 0; }
63 };
64 
65 #endif