【发布时间】:2011-12-16 10:19:25
【问题描述】:
我几天前看到的一个小而非常讨厌的问题,在面试时问我的朋友。
最初的面试问题是:“以下代码的输出是什么?”
int i = 2;
i = i++ + i++;
正确答案是 ((2 + 2) + 1) + 1 = 6,即在赋值之前应用两次后增量,但在加法之后。
然后我想创建一个带有一个整数的简单类,并重载 operator+() 和 operator++(int) 以在日志中查看执行运算符的确切顺序。
这是我得到的:
class A
{
public:
A(int _data) : data(_data) { }
A &operator=(const A& _rhs)
{
data = _rhs.data;
cout<<" -- assign: "<<data<<endl;
}
A operator++(int _unused)
{
A _tmp = data;
data++;
cout<<" -- post-increment: "<<data<<endl;
return _tmp;
}
A operator+(const A &_rhs)
{
A _tmp = data + _rhs.data;
cout<<" -- addition: "<<data<<"+"<<_rhs.data<<endl;
return _tmp;
}
inline operator int() const { return data; }
private:
int data;
};
结果令人沮丧:
-- post-increment: 3
-- post-increment: 4
-- addition: 3+2
-- assign: 5
对于不太复杂的构造,例如 (A _dt2 = a++; ),它会按照应有的方式运行,但运算符的执行顺序与整数类型不同。
我猜这可能是编译器特定的问题:
$ gcc --version
gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
所以,我有点迷路了:)
【问题讨论】:
-
我很确定第一个截图的输出是未定义的
-
是的,第一个 sn-p 有未定义的行为。
-
隐藏的采访 Q 是:
Can you detect that this is Undefined Behavior? -
@Als:感谢您提供更好的链接来提供我的答案,但它不是直接重复的。该问题的主要主题是模拟类 wrt 之类的整数。增量。