gpt4 book ai didi

c++ - 保持平等和稳定有什么区别?

转载 作者:搜寻专家 更新时间:2023-10-31 01:24:32 24 4
gpt4 key购买 nike

根据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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com