Using a delegate stored as a member of a destroyed struct?
Nicolas Sicard
dransic at gmail.com
Sun Jan 26 15:41:00 PST 2014
Running a piece of code that can be reduced to:
---
import std.stdio;
void main()
{
import std.range;
foreach(item; iota(0, 10).transform(2))
writeln(item);
}
auto transform(T)(T list, real x)
{
auto t = /* new */ Transformer(x); // line 12
return t.applyTo(list);
}
struct Transformer
{
real delegate(real) fun;
this(real x)
{
fun = (real r) => r * x;
}
auto applyTo(T)(T list)
{
import std.algorithm;
return list.map!(x => fun(x));
}
}
---
the program segfaults. I guess it's because fun is destroyed when
't' goes out of scope in 'transform'. I would have thought that
the MapResult struct returned by 'applyTo' still holds a valid
copy of fun, but I'm wrong... Is there a way to do it?
Of course, uncommenting 'new' on line 12 resolves the problem.
Thanks,
Nicolas
More information about the Digitalmars-d-learn
mailing list