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

Naz*_*nho 7 c++ language-lawyer c++-concepts

根据草案

如果给定相同的输入,表达式会产生相同的输出,则该表达式是保持相等的。[ ... ]

[...]稳定:具有相同输入对象的此类表达式的两次评估需要具有相同的输出,而无需对这些输入对象进行任何显式干预修改。[...]

强调我的。

  • 这些有什么区别?

  • 什么时候一个表达式可以保持相等不稳定反之亦然

Jer*_*fin 6

对于修改其输入的操作来说,这两者是不同的。

// 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;
}
Run Code Online (Sandbox Code Playgroud)

例如:

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
Run Code Online (Sandbox Code Playgroud)

至于稳定但不保持平等的东西,是的,这也是可能的(对于“平等”的某些定义)。

举一个简单的例子,考虑这样的事情:

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;
Run Code Online (Sandbox Code Playgroud)