The goal:
I would like to have a range checked version of std::vector
's operator []
for my debug builds and no range check in release mode.
The range check in debug mode is obviously good for debugging, but it causes a slowdown of 5% - 10% in my release code which I would like to avoid.
Possible solutions:
I found a solution in Stroustrup's "The C++ programming language". He did the following:
template <class T>
class checked_vector : public std::vector<T> {
public:
using std::vector<T>::vector;
//override operator [] with at()
};
This is problematic because it inherits from a class with non-virtual destructor which is dangerous. (And the Lounge was not too fond of that solution.)
Another idea would be a class like this:
template <class T>
class checked_vector {
std::vector<T> data_;
public:
//put all public methods of std::vector here by hand
};
This would be both tedious and create a large amount of copy-paste which is bad too.
The nice thing about both the above solutions is that I can simply toggle them on and off with a macro definition in my makefile.
The questions:
- Is there a better solution? (If not, why not?)
- If not, is one of the above considered acceptable? (I know this one is opinion based, please focus on No. 1 if possible.)