c++vectorboundary

Convert between vector::operator[] and vector::at in C++


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?


Solution

  • 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.