On Sunday, 5 June 2022 at 17:04:49 UTC, Ali Çehreli wrote:
On 6/5/22 08:07, kdevel wrote:
[...]
Like many other programmers who include me, Sean Parent may be
right.[1]
Other than being a trivial example to make a point, the code
I've shown may be taking advantage of the "structure of array"
optimization.
"Premature optimization is ..."
[...]
> struct T {
> int a;
> int b;
> }
>
> struct S {
> T [] t;
>
> void add(int i) {
> t ~= T (i, i * 10);
> }
>
> void foo() {
> // Look Ma no assert!
The assert may have been moved to another place:
It's not "the" assert but another one. Nonetheless I take up the
challenge:
struct T {
int a;
int b;
invariant() {
// Look Pa it's still here!
assert(b == a * 10);
}
}
struct T {
int i;
this (int i)
{
this.i = i;
import std.checkedint;
Checked!(int, Throw) (i) * 10;
}
int a () const { return i; }
int b () const { return i * 10; }
}
struct S {
const (T) [] t;
void add(int i) { // <-- Both arrays always same size
t ~= T (i);
}
void foo() {
// ...
}
}
void main() {
auto s = S();
s.add(42);
s.foo();
// s.a ~= 1; // does not compile
// s.t[0].b = 3; // no compile either
// s.t[0].i = 7; // cannot change i, does not compile
s.add (2^^27); // fine
// s.add (2^^28); // throws Overflow on binary operator, fine
s.foo();
}
Ali
[...]
I'll try to not bring up his name again ;-)