0

vector::at are quite helpful for boundary checking, but will lead to low speed. So I am wondering whether there is a way to quickly convert code between vector::operator[] and vector::at, so that one for release and one for debug. Like

If (DEBUG)
{
// Do with .at
}
else
{
// Do with []
}

However, using code like that will import risk that when Do with .at are changed, Do with [] are forgotten to be changed accordingly.

Is there a quick way to convert code between two modes?

wznmickey
  • 35
  • 6
  • 1
    I think that is simply called operator[]. If your standard library is good, then it already has extra checks in debug mode. – user253751 Jun 02 '22 at 16:41
  • 1
    Which compiler and STL are you using? MS STL already does [bound check with `[]` in debug mode](https://stackoverflow.com/a/1290586/995714). And debug/release flag is a compile time setting so you'll need a macro, not a runtime thing like `if` – phuclv Jun 02 '22 at 16:42
  • There's no real cost using `at()` with release ready production code. So why change it?? – πάντα ῥεῖ Jun 02 '22 at 16:43
  • [Automatically check bounds in std::vector](https://stackoverflow.com/q/48035379/995714), [Compile time triggered range check for std::vector](https://stackoverflow.com/q/24246017/995714) – phuclv Jun 02 '22 at 16:44
  • 3
    *but will lead to low speed* -- `if ( index >= size )` -- What type of application are you developing where the `if` statement will result in such a "low speed"? – PaulMcKenzie Jun 02 '22 at 16:47
  • First should should benchmark your code and actually show a slowdown for vector::at. Often the check can be optimized away or can be done while waiting for some other opcodes and the difference is well below the noise level. On the other hand a single cought bounds check can save you hours. – Goswin von Brederlow Jun 02 '22 at 18:02

1 Answers1

3

Like

If (DEBUG)
{
// Do with .at
}
else
{
// Do with []
}

You get something like this by using operator[] and by enabling bounds checking debug mode of the standard library implementation that you use. How to do that, and whether that option exists depends on what implementation you use.

Note that typically the entire project, including all libraries must have been built with the same standard library options. This is a potential problem if you use pre-built libraries.

A universally portable solution is to write a wrapper function that conditionally calls one function or the other depending on build configuration. Downside is that this requires changing all code using the wrapped function to use the custom one.

eerorika
  • 232,697
  • 12
  • 197
  • 326