Disabling bounds checking for c++ vectors

前端 未结 8 2417
囚心锁ツ
囚心锁ツ 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:45

    Use at() when you always want checking. Also note that this throws an exception on error, so it is potentially recoverable. If you want the faster, unchecked, accessor, use [], but algorithms that use this should be tested thoroughly because the failure mode is more severe (undefined behavior).

    A couple of approaches to development-mode bounds checking for [] when using GCC on Linux:

    • Enable GCC debug mode, see also GCC STL bound checking

      -D_GLIBCXX_DEBUG

    • Run your program under the Valgrind memory checker

      valgrind (your program and args)

    Some other interesting discussion: vector::at vs. vector::operator[]

提交回复
热议问题