下面的代码演示了这种差异:
#include <iostream>
#include <string>
int main()
{
char s[] = "ABCD";
std::string str(s);
char *p = s;
while(*p) {
*p++ = tolower(*p); // <-- incr after assignment
}
std::cout << s << std::endl;
std::string::iterator it = str.begin(), end = str.end();
while(it != end) {
*it++ = tolower(*it); // <-- incr before assignment ?
}
std::cout << str << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它产生输出:
abcd
bcd
Run Code Online (Sandbox Code Playgroud)
如果我们分配赋值操作和增量运算符:
while(it != end) {
*it = tolower(*it); // <-- incr before assignment ?
it++;
}
Run Code Online (Sandbox Code Playgroud)
输出将如预期.
原始代码有什么问题?
$ g++ --version
g++ (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
Copyright (C) 2004 Free Software Foundation, Inc.
Run Code Online (Sandbox Code Playgroud)
问题是参数的评估顺序operator=
是未指定的.这是根据C++标准5.2.2/8.考虑以下:
*it++ = tolower(*it);
Run Code Online (Sandbox Code Playgroud)
等于
operator=( *it++, tolower(*it) );
Run Code Online (Sandbox Code Playgroud)
现在*it++
可以在之前计算tolower(*it)
,反之亦然.
归档时间: |
|
查看次数: |
343 次 |
最近记录: |