During active development of a class that uses std::vector
, it often happens that an index is out of bounds. (See this code review question for a practical example.) When using operator[]
, this results in undefined behavior. Still, the []
syntax is easy to read an more convenient than writing .at()
.
Therefore I'd like to write my code using the []
operator, but at the same time have bounds checks enabled. After testing the code, it should be very easy to remove the bounds checks.
I'm thinking of the following code:
util::bound_checked<std::vector<int>> numbers;
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(4);
std::cout << numbers[17] << "\n";
To me, this utility template seems to be so straight-forward that I'd expect it to exist. Does it? If so, under which name?
If you use GCC (possibly MinGW), or Clang with libstdc++ (GCC's standard library), then #define _GLIBCXX_DEBUG
will do what you want.
Or even better, define it with a flag: -D_GLIBCXX_DEBUG
.
Alternatively, there's also _GLIBCXX_ASSERTIONS
, which performs less checks, but compiles (and presumably runs) faster.
To me, this utility template seems to be so straight-forward that I'd expect it to exist
For gcc it does exist. gcc libstdc++ has a set of debug containers. For std::vector
it has __gnu_debug::vector
debug container. See documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With