Reference:
Equality preservation
Equality Preservation is a rule that says a function (or expression) must be "well-behaved" and "predictable."
It essentially means: If you give it the same inputs, you should get the same outputs.
- The Core Idea: "No Surprises"
If we have two objects, a and b, and they are equal (a == b), then doing the same thing to both of them should result in the same outcome.
Equal Inputs -> Equal Results: If f(a) returns 5, and a == b, then f(b) must also return 5.
Equal Inputs -> Equal Side Effects: If calling f(a) changes a to 10, then calling f(b) must change b to 10.
- The Requirement of "Stability"
The standard also requires equality-preserving expressions to be stable. This means if we haven't changed the object ourselves, calling the function twice on the same object must give the same result both times.
Example of something NOT stable:
A function that returns a random number or a function that uses a global counter that increments every time you call it. i.e. has no Referential transparency
A function that returns a random number or a function that uses a global counter that increments every time you call it. i.e. has no Referential transparency
int counter = 0;
int bad_function(int x) { return x + (counter++); } // NOT equality-preserving
By requiring concepts to be equality-preserving, C++ guarantees that:
- The algorithm can trust the values it reads.
- The algorithm can safely make copies of objects and expect the copies to behave exactly like the originals.
Unless noted otherwise, every expression used in a requires expression of the standard library concepts is required to be equality preserving, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
In the standard library, the following concepts are allowed to have non equality-preserving requires expressions:
- output_iterator
- indirectly_writable
- invocable
- weakly_incrementable
- range
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.