禁用对c ++向量的边界检查

mat*_*ash 11 c++ g++ libstdc++

使用stl :: vector:

vector<int> v(1);
v[0]=1; // No bounds checking
v.at(0)=1; // Bounds checking
Run Code Online (Sandbox Code Playgroud)

有没有一种方法来禁用边界检查,而不必重写所有at()[]?我正在使用GNU标准C++库.

编辑:我改变了at()[]在我怀疑的瓶颈区域,并显著减少了计算时间.但是,由于我在开发代码和运行实验之间进行迭代,我想在开发过程中启用边界检查,并在运行实验时禁用它.我想安德鲁的建议是最好的解决方案.

And*_*ein 24

如果你真的想这样做(至少对于快速和脏的分析比较),如果没有其他at()的,这将有效

#define at(x) operator[](x)
Run Code Online (Sandbox Code Playgroud)

如果你想继续at()开发和operator[]在生产中使用,只需将它包装成一个#ifdef.

如果你有其他at()的,你可以随时编辑你的#included <vector>文件.


Chr*_*ung 15

否.边界检查std::vector::at由标准指定,并且没有符合标准的C++实现可能与此不同.


Fre*_*son 6

也许更好的解决方案是使用[]和使用标准库的已检查实现进行调试.


R S*_*hko 5

根据您想要打开/关闭边界检查的注释,您可以使用包装器模板函数:

template <class T>
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 <class T>
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
}
Run Code Online (Sandbox Code Playgroud)

您必须修改您的代码才能启用此功能,但是一旦您将其安装到位,您可以根据需要打开或关闭绑定检查.

我承认使用它看起来有点难看:

deref(vec, 10) = ...;
Run Code Online (Sandbox Code Playgroud)