How to make std::vector#39;s operator[] compile doing bounds checking in DEBUG but not in RELEASE(如何使 std::vector 的 operator[] 编译在 DEBUG 中进行边界检查而不是在 RELEASE 中)
问题描述
我使用的是 Visual Studio 2008.
I'm using Visual Studio 2008.
我知道 std::vector 会使用 at() 函数进行边界检查,并且如果您尝试使用运算符 [] 错误地(超出范围)访问某些内容,则会出现未定义的行为.
I'm aware that std::vector has bounds checking with the at() function and has undefined behaviour if you try to access something using the operator [] incorrectly (out of range).
我很好奇是否可以通过边界检查来编译我的程序.这样,operator[] 将使用 at() 函数并在某些内容超出范围时抛出 std::out_of_range .
I'm curious if it's possible to compile my program with the bounds checking. This way the operator[] would use the at() function and throw a std::out_of_range whenever something is out of bounds.
发布模式编译时不会对operator[]进行边界检查,因此性能不会下降.
The release mode would be compiled without bounds checking for operator[], so the performance doesn't degrade.
我开始考虑这个是因为我正在将一个使用 Borland C++ 编写的应用程序迁移到 Visual Studio,并且在一小部分代码中我有这个(i=0,j=1):
I came into thinking about this because I'm migrating an app that was written using Borland C++ to Visual Studio and in a small part of the code I have this (with i=0, j=1):
v[i][j]; //v is a std::vector<std::vector<int> >
向量'v'的大小是[0][1](所以向量的元素0只有一个元素).这是未定义的行为,我知道,但 Borland 在这里返回 0,VS 正在崩溃.我更喜欢崩溃而不是返回 0,所以如果我可以通过抛出 std::out_of_range 异常获得更多崩溃",迁移将完成得更快(因此它会暴露更多 Borland 隐藏的错误).
The size of the vector 'v' is [0][1] (so element 0 of the vector has only one element). This is undefined behaviour, I know, but Borland is returning 0 here, VS is crashing. I like the crash better than returning 0, so if I can get more 'crashes' by the std::out_of_range exception being thrown, the migration would be completed faster (so it would expose more bugs that Borland was hiding).
推荐答案
Visual Studio 2005 和 2008 已经默认对 operator[]
进行边界检查,两者调试和发布版本.
Visual Studio 2005 and 2008 already do bounds-checking on operator[]
by default, in both debug and release builds.
控制这种行为的宏是_SECURE_SCL
.将其设置为 0 以禁用边界检查.
The macro to control this behavior is _SECURE_SCL
. Set it to 0 to disable bounds-checking.
他们在 VS2010 中的当前计划是在发布版本中默认禁用边界检查,但在调试中保持启用.(该宏也被重命名为 _ITERATOR_DEBUG_LEVEL
.我不知道是否有任何关于它的正式文档,但已经提到了 此处 和 这里)
Their current plan in VS2010 is to disable bounds-checking by default in release builds, but keep it on in debug. (The macro is also getting renamed to _ITERATOR_DEBUG_LEVEL
. I don't know if there's any formal documentation available on it yet, but it has been mentioned here and here)
这篇关于如何使 std::vector 的 operator[] 编译在 DEBUG 中进行边界检查而不是在 RELEASE 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使 std::vector 的 operator[] 编译在 DEBUG 中进行边界检查而不是在 RELEASE 中
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01