Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically check bounds in std::vector [duplicate]

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?

like image 427
Roland Illig Avatar asked Dec 30 '17 15:12

Roland Illig


2 Answers

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.

like image 177
HolyBlackCat Avatar answered Nov 09 '22 23:11

HolyBlackCat


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.

like image 28
ks1322 Avatar answered Nov 10 '22 01:11

ks1322