libsidplayfp  1.0.3
array.h
00001 /*
00002  * This file is part of libsidplayfp, a SID player engine.
00003  *
00004  *  Copyright (C) 2011 Leandro Nini
00005  *
00006  *  This program is free software; you can redistribute it and/or modify
00007  *  it under the terms of the GNU General Public License as published by
00008  *  the Free Software Foundation; either version 2 of the License, or
00009  *  (at your option) any later version.
00010  *
00011  *  This program is distributed in the hope that it will be useful,
00012  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014  *  GNU General Public License for more details.
00015  *
00016  *  You should have received a copy of the GNU General Public License
00017  *  along with this program; if not, write to the Free Software
00018  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
00019  */
00020 
00021 #ifndef ARRAY_H
00022 #define ARRAY_H
00023 
00026 class counter
00027 {
00028 private:
00029     unsigned int c;
00030 
00031 public:
00032     counter() : c(1) {}
00033     void increase() { ++c; }
00034     unsigned int decrease() { return --c; }
00035 };
00036 
00040 template<typename T>
00041 class array
00042 {
00043 private:
00044     counter* count;
00045     unsigned int x, y;
00046     T* data;
00047 
00048 public:
00049     array(unsigned int x, unsigned int y) :
00050         count(new counter()),
00051         x(x),
00052         y(y),
00053         data(new T[x* y]) {}
00054 
00055     array(const array& p) :
00056         count(p.count),
00057         x(p.x),
00058         y(p.y),
00059         data(p.data) { count->increase(); }
00060 
00061     ~array() { if (count->decrease() == 0) { delete count; delete [] data; } }
00062 
00063     unsigned int length() const { return x * y; }
00064 
00065     T* operator[](unsigned int a) { return a < x ? &data[a * y] : 0; }
00066 
00067     T const* operator[](unsigned int a) const { return a < x ? &data[a * y] : 0; }
00068 };
00069 
00070 #endif