根据draft :
An expression is equality-preserving if, given equal inputs, the expression results in equal outputs.[...]
和
[...]stable: two evaluations of such an expression with the same input objects are required to have equal outputs absent any explicit intervening modification of those input objects.[...]
强调我的。
这些有什么区别?
什么时候表达式可以保持相等但不是稳定和反之亦然?
最佳答案
对于修改其输入的操作,两者会有所不同。
// stable and equality preserving
int foo(int a, int b) {
return a + b;
}
// equality preserving, but not stable:
int bar(int a, int &b) {
auto ret = a + b;
++b;
return ret;
}
例如:
int x = 1, y = 2;
int z = foo(x, y); // produces 3
int z2 = foo(x, y); // still produces 3
int zz = bar(x, y); // produces 3
int zz2 = bar(x, y); // produces 4
至于稳定但不保持相等的东西,是的,这也是可能的(对于“相等”的某些定义)。
举一个简单的例子,考虑这样的事情:
struct foo {
int bar;
// they're all equal, just some are more equal than others
bool operator==(foo const &) const { return true; }
};
int operator+(foo a, foo b) { return a.bar + b.bar; }
foo a{1};
foo b{2};
foo c{3};
// obviously both true
assert(a == b);
assert(b == c);
int x = a + b;
int y = b + c;
assert(x != y); // of course 1 + 2 != 2 + 3;
关于c++ - 保持平等和稳定有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58109930/