#29088 - sajiimori - Thu Nov 11, 2004 6:59 am
I've been trying to figure out how to implement generic bounds-checked arrays that are as efficient as C arrays (when bounds checking is disabled) and can be initialized during declaration. Here's a naive attempt at such a class:
At least with GCC, using it involves an extra dereference in comparison to regular arrays. Even if everything is declared const, GCC can't figure out that mData is equivalent to the initializer. So, it seems necessary for the object to actually contain the array, like this:
But how could such an object be initialized during declaration?
Edit: On second thought, the inefficiency of the first version is inconsequential. Since the difference between regular arrays and bounds-checked arrays is only relevant for debug builds, I can simply switch to regular arrays for release builds.
The new questions are: How do I declare the first version gracefully, without having to declare the C array and the wrapper seperately? And then how do I change to standard arrays transparently?
I just know the answer is gonna be "macros", but if there's another way, I'd definitely like to find it.
Code: |
template<class T, int SIZE>
class Array { public: Array(T data[SIZE]) : mData(data) {} T& operator[](int i) { assert(i >= 0 && i < SIZE); return mData[i]; } private: T* const mData; }; |
Code: |
template<class T, int SIZE>
class Array { public: T& operator[](int i) { assert(i >= 0 && i < SIZE); return mData[i]; } private: T mData[SIZE]; }; |
Edit: On second thought, the inefficiency of the first version is inconsequential. Since the difference between regular arrays and bounds-checked arrays is only relevant for debug builds, I can simply switch to regular arrays for release builds.
The new questions are: How do I declare the first version gracefully, without having to declare the C array and the wrapper seperately? And then how do I change to standard arrays transparently?
I just know the answer is gonna be "macros", but if there's another way, I'd definitely like to find it.