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

标签 c++ language-lawyer c++-concepts

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

相关文章:

c++ - Xcode/Clang 魔法数字?

c++ - (int&&)5 是整数常量表达式吗?

c - C编程中,要求L值是语义错误还是语法错误?

c++ - 带有 boolean 值的 ASSERT_EQ 在 gtest 中失败

c++ - 用户定义的类序列化、C++ 和 msgpack

c++ - 与静态库链接时,为什么要强制执行命令(例如source.cxx -lstatic)?

c++ - 可观察的行为和未定义的行为——如果我不调用析构函数会发生什么?

c++ - 从使用概念定义的函数返回新对象

c++ - 用 C++ 编写和检查自己的概念

c++ - 如何为概念重载函数?