Disabling bounds checking for c++ vectors

前端 未结 8 2450
囚心锁ツ
囚心锁ツ 2021-02-08 06:09

With stl::vector:

vector v(1);
v[0]=1; // No bounds checking
v.at(0)=1; // Bounds checking

Is there a way to disable bounds checking

8条回答
  •  南旧
    南旧 (楼主)
    2021-02-08 06:30

    Based on your comment that you would like to turn on/off bounds checking, you could use a wrapper template function:

    template 
    inline typename T::reference deref(T &cont, typename T::size_type idx)
    {
    #if BOUNDS_CHECK
        return cont.at(idx);
    #else
        return cont[idx];
    #endif
    }
    
    template 
    inline typename T::const_reference deref(const T &cont, typename T::size_type idx)
    {
    #if BOUNDS_CHECK
        return cont.at(idx);
    #else
        return cont[idx];
    #endif
    }
    

    You would have to modify your code to enable this, but once you had it in place you could turn bound checking on or off as you wish.

    I do admit that it looks a bit ugly to use:

    deref(vec, 10) = ...;
    

提交回复
热议问题