Skip to content

Instantly share code, notes, and snippets.

@sundeepblue
Created April 7, 2014 19:21
Show Gist options
  • Save sundeepblue/10034600 to your computer and use it in GitHub Desktop.
Save sundeepblue/10034600 to your computer and use it in GitHub Desktop.
create an array class with bounds checking
template <typename T, unsigned int N>
class SafeArray {
protected:
T a[N];
public:
SafeArray() {
memset(a, 0, sizeof(a));
}
int size() { return N; }
T& operator[] (unsigned int i) {
if(i >= N) // index out of range, return a null reference to provoke error
return *(T*)0;
return a[i];
}
};
int main() {
// usage of SafeArray
SafeArray<float, 100> list;
for(int i=0; i<list.size(); ++i)
cout << list[i] << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment