Disabling bounds checking for c++ vectors

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

    Derive your own vector class in your own namespace like "uncheckedvector", and override the at() of the base vector type to use the array index.

    Then use "using uncheckedvector::vector" will let you override all your uses of vector everywhere. This won't work if you're using fully qualified types anywhere though.

    0 讨论(0)
  • 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[]

    0 讨论(0)
提交回复
热议问题