`restricted` member variables
Ola Fosheim Grøstad
ola.fosheim.grostad at gmail.com
Tue Jun 21 11:20:46 UTC 2022
On Tuesday, 21 June 2022 at 10:36:32 UTC, The Zealot wrote:
> if anything, i'd like to see more control over when invariants
> are actually checked.
>
> something like
> ```
> invariant(default)
> {
> assert(1 <= day && day <= 31);
> assert(0 <= hour && hour < 24);
> }
> invariant(always) {
> assert(1 <= sec && sec <= 60);
> }
> ```
You can already do this, just add an or-clause to a compile time
boolean constant.
```d
assert((!precise_invariant) || (1 <= day && day <= 31));
```
But the class invariant should only be tested on member-function
entry in debug-mode.
In release mode the invariant should be assumed to hold on entry
and can be used for optimizations (it should still be tested on
exit).
So this:
```d
class always_even {
private int x;
invariant { assert(x%2==0); }
void triple(){
x *= 3;
if (x&1) writeln("found one");
}
// more code
}
```
should become this:
```d
class always_even {
private int x;
tripple(){
// assume(x%2==0)
x *= 3;
assert(x%2==0);
}
…
}
```
Or even this (with a decent optimizer):
```d
class always_even {
private int x;
tripple(){
// assume(x%2==0)
x *= 3;
// assert(x%2==0);
}
…
}
```
With invariants turned off, the result will be worse as there is
no indication that the lowest bit of x is constant 0:
```d
class always_even {
private int x;
void triple(){
x *= 3;
if (x&1) writeln("found one");
}
…
}
```
More information about the Digitalmars-d
mailing list