如何使 std::vector 的 operator[] 编译在 DEBUG 中进行边界检查而不是在 RELEASE 中

How to make std::vector#39;s operator[] compile doing bounds checking in DEBUG but not in RELEASE(如何使 std::vector 的 operator[] 编译在 DEBUG 中进行边界检查而不是在 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 中

基础教程推荐