“Out” parameters and destructors
Ogi
ogion.art at gmail.com
Sat Mar 15 11:44:14 UTC 2025
On Friday, 14 March 2025 at 16:54:10 UTC, Ali Çehreli wrote:
> Although understandably undesirable, this is according to spec:
>
> https://dlang.org/spec/function.html#ref-params
>
> "An out parameter [...] is initialized with x.init upon
> function invocation."
I want to clarify if this is intentional or not, and what is the
intention if it is. Currently, it turns out that the variable has
to be destroyed before passing it as an “out” argument. It’s
counter-intuitive, and it defeats the purpose of “out” parameters.
> Perhaps the compiler should not allow using constructed objects
> as 'out' parameter arguments.
In this aspect, current implementation differs from spec, so it
handles constructed objects correctly. The “out” parameter is not
initialized with `.init`, it’s *default-initialized*:
```D
void main() {
import std.stdio;
int x;
struct S {
void bumpX() { x++; }
}
void foo(out S s) {}
S s = S.init;
foo(s);
s.bumpX();
writeln(x);
}
```
If `S` would be initialized with `.init`, the hidden context
pointer in the nested struct would be null, and calling to
`bumpX()` would crash the program. But it doesn’t crash and
prints: `1`.
More information about the Digitalmars-d
mailing list