0

I find vector::at() useful for alerting against out-of-bounds bugs while debugging, but it's painfully slow and unsuited for release code. Is there a known compiler flag or some method to automatically convert vector::at() to vector::operator[] when compiling in release mode, sort of like how asserts() are stripped in release with DNDEBUG?

Edit: Follow the linked question for a solution to this, or check the accepted answer (+ the comments below this question for some compiler specific stuff). Basically, this problem can be solved in reverse (there are options to allow bounds checking for vector::operator[] in debug mode).

Ian Chu
  • 2,924
  • 9
  • 14
  • AFAIK `operator[]` for msvc already does checking in debug mode. – Marek R Dec 07 '21 at 15:06
  • 2
    In Debug (in MSVC) `operator[]` will use `_ITERATOR_DEBUG_LEVEL` already to throw runtime exceptions for out of bounds violations, and in Release this will simply be undefined behavior if out of bounds. – Cory Kramer Dec 07 '21 at 15:07
  • oh, thank you, I wasn't aware that this was already an option. That makes sense. – Ian Chu Dec 07 '21 at 15:09
  • 1
    and for clang and gcc just add `-fsanitize=address` to catch lots of different memory errors. MSVC has this tool too as experimental feature. – Marek R Dec 07 '21 at 15:10

1 Answers1

2

If you want no bounds checking overhead at runtime, then use the subscript operator.

With most standard library implementations, you can enable non-standard bounds checking in subscript operator. Usually by defining a macro. This has a caveat, that the entire program must be compiled in the same mode, including any linked libraries.

Address/UB sanitisers should also be used when testing and debugging, and they may also detect typical buffer overflow conditions in absence of standard library support.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • can you add the specifics for MSVC, gcc, and clang (Kramer and Marek's comments)? Your general answer is useful, but I think it'd help to have the common, compiler-specific options as well. – Ian Chu Dec 07 '21 at 15:16
  • @IanChu I'd rather keep my answer generic so that it applies to all compilers. You can check the manual of your compiler for how to enable debug mode and sanitisers. – eerorika Dec 07 '21 at 15:19