Idea for avoiding GC for lambdas
H. S. Teoh
hsteoh at quickfur.ath.cx
Tue Jun 22 21:31:48 UTC 2021
On Tue, Jun 22, 2021 at 03:56:03PM -0400, Steven Schveighoffer via Digitalmars-d wrote:
[...]
> This again, is a misunderstanding of my proposal. I'm not talking
> about altering delegates in any way.
>
> There are no delegates involved in `filter`. It is, instead, an inner
> struct with a hidden context pointer. Could just as well be a struct
> with context carried with it instead of allocated on the heap.
[...]
Ohhh I see what you mean now. So essentially what you're saying is,
whenever there's an alias parameter bound to a lambda, the compiler
should, in effect, insert additional parameters to the template
function that captures the context the lambda is bound to?
IOW, this:
auto filter(alias fun, R)(R range) {
struct Voldemort {
...
if (fun(range.front)) ...
...
}
return Voldemort(range);
}
int x = 2, y = 3;
auto r = [1, 2, 3].filter!(e => e == x || e == y);
gets lowered into something like this:
struct __lambda_context {
int x, y;
}
bool __lambda_fun(__lambda_context ctxt, int e) {
return e == ctxt.x || e == ctxt.y;
}
auto __filter_instance(R)(__lambda_context ctxt, R range) {
struct Voldemort {
__lambda_context secretCtxt;
...
if (__lambda_fun(secretCtxt, range.front)) ...
...
}
return Voldemort(ctxt, range);
}
int x = 2, y = 3;
auto r = __filter_instance(__lambda_context(x, y), [1, 2, 3]);
Am I right?
__lambda_context may not necessarily carry a copy of the captured
variables; possibly it could use pointers instead. Though care would
have to be taken not to leave dangling pointers to out-of-scope local
variables -- probably you'd have to make the references `scope` unless
you copy them by value into the Voldemort struct.
T
--
Не дорог подарок, дорога любовь.
More information about the Digitalmars-d
mailing list