6

If I try to access an std::vector out of bounds it will lead to undefined behaviour.

const std::vector<int> vec {1,2,3};
const int a = vec[4];

Nevertheless, this code will probably not fail immediately, but a will have an arbitrary value;

If vec is accessed via the method .at() an exception will be thrown.

const int a = vec.at(4);

The disadvantage is, that the performance will drop significantly if .at() is always used.

My question is, if some C++ compiler supports a compile flag, that switches the operator [] to the .at() method.

Turing it on would lead to good debug-able code. Turing it off would lead to a quick release executable.

I know that heap check tools , such as valgrind will find these bugs, but they take a lot of time.

schorsch312
  • 5,553
  • 5
  • 28
  • 57
  • You could write your own vector implementation, and switch by changing `using schorsch312::vector;` to `using std::vector;`. Possibly using `#ifdef NDEBUG` around it. – Eljay Jun 01 '18 at 13:02
  • 1
    I think you need to be specific about your compiler. UB means the compiler can do anything it wants - like throw if it's been compiled in debug – UKMonkey Jun 01 '18 at 13:02
  • 4
    MSVC already supports bounds checking for `operator[]` with debug. – Hatted Rooster Jun 01 '18 at 13:02
  • 1
    which compiler are you working on? Because MSVC already does it while Clang (eg macOS) can enable address sanitizer which covers this situaton. – Jack Jun 01 '18 at 13:05
  • 2
    @Clonk: because `at()` does bound checking also in release mode so it's an `O(k1)` different from `O(k2)` of `operator[]`. Complexity is the same but on millions of calls you can see a difference. – Jack Jun 01 '18 at 13:06
  • @Clonk Constant complexity only applies to algorithms. – Rakete1111 Jun 01 '18 at 13:08
  • Also https://stackoverflow.com/q/24246017/3002139 Some Mjolnir should clean this up. – Baum mit Augen Jun 01 '18 at 13:21

0 Answers0