本文介绍了如何使std :: vector的运算符[]编译做边界检查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).

我很好奇,如果可以使用bounds检查来编译我的程序。这样,运算符[]将使用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.

检查运算符[],所以性能不会降低。

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]向量只有一个元素)。这是未定义的行为,我知道,但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.

控制此行为的宏是。

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的运算符[]编译做边界检查DEBUG但不是在RELEASE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:54