Windows 7 64 SP1, 提升 1.42, MS VS 2010 终极版, C++语言
这段精简代码使用这些开关在“Visual Studio x64 命令提示符 (2010)”中编译并运行良好:
cl/EHsc/W4/nologo
#include <string>
using namespace std; // I know not to use.
int main() {
string sentence = "abc";
string word_found = "";
string::const_iterator it = sentence.begin();
while ( *it != ' ' && it != sentence.end() )
word_found += *it++;
}
但是,在 VS IDE 中编译后,运行时,它崩溃并出现错误:
Expression: string iterator not dereferencable
问题显然出在 ( *it != ' ' && it != sentence.end() )
中的 *it
。我只需要将表达式短路,这样现在右边的表达式 *it != ' '
就不会求值:
while ( it != sentence.end() && *it != ' ' )
然后它运行良好。
但为什么在命令提示符下编译原始代码后它运行完美?在这个子集派生的更大的程序中没有其他异常行为。 string::iterator 不会导致同样的问题是什么?
FWIW,这些是默认的 MS VS 命令行选项:/ZI/nologo/W3/WX-/Od/Oy-/D "WIN32"/D "_DEBUG"/D "_CONSOLE"/D "_UNICODE"/D "UNICODE"/Gm/EHsc/RTC1/GS/fp:precise/Zc:wchar_t/Zc:forScope/Fp"Debug\test short.pch"/Fa"Debug\"/Fo"Debug\"/fd"Debug\vc100.pdb"/Gd/analyze-/errorReport:queue
为什么命令行编译器和IDE编译器生成不同的可执行文件?有没有我可以添加到命令提示符编译器的开关,使可执行文件的行为方式与从 VS IDE 编译时的行为方式相同
最佳答案
这些运行时检查仅在调试 构建中默认启用。你要么需要
通过使用 the
/MDd
or/MTd
option 进行编译,使用调试运行时之一进行构建,或者通过更改
_ITERATOR_DEBUG_LEVEL
启用检查迭代器到1
(/D_ITERATOR_DEBUG_LEVEL=1
)。
关于c++ - 为什么在从控制台编译后取消引用 string::iterator 不会在 .end() 处引发错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12695101/