Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap between at() and operator[] for std::vector depending on compile switch/NDEBUG

Tags:

c++

clang++

I know that g++ (and MSVC) have switches that allow bounds checking on operator[] , unfortunately, to my knowledge, LLVM's libc++ doesn't have a complete implementation of such switches or debug code.

On my current project I have been using my own implementation of vector (that I wrote for portability a few years back) which doesn't throw exceptions and has assert based bounds checking on operator[] and at (in fact one calls the other and they behave identically as there are no exceptions).

I'm going to be handing over this code-base after I've finished my current program and it may be in use for a long time. Since I'm not supposed to be required to maintain it or anything I would rather be fully standard compliant everywhere and I don't feel that re-implementing a container is in the spirit of the standard, (I also highly doubt that my container is as good as one written by the libc++ or libstdc++ team).

Is there some preprocessor magic or similar that I can do to make operator[] behave like at() during debug (so it aborts due to an uncaught exception) and behave like operator[] when I disable this debug mode? (Project is fully C++14 supported)

like image 942
Goobley Avatar asked Apr 27 '26 08:04

Goobley


1 Answers

We can see from the trunk libc++ source code for vector that there is indeed such a check inside std::vector<>::operator[], which goes through _LIBCPP_ASSERT.

Unfortunately, the libc++ debug feature is not yet functional.

So:

  • Watch for libc++ updates
  • Train your team to expect operator[] to silently accept broken input. That's what it does, by definition. Coming to rely on implementation-specific additional sanity checks is a really bad idea. Your team should be writing their own asserts if they're not sure what they're doing.
like image 151
Lightness Races in Orbit Avatar answered Apr 29 '26 22:04

Lightness Races in Orbit