what is the point of functor ?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Jun 22 20:14:42 UTC 2018


On Friday, June 22, 2018 14:06:06 Flaze07 via Digitalmars-d-learn wrote:
> recently, I visited the glossary and saw that functor exist in
> D...I know that functor exist C++ as a way to easily allow higher
> order function, but since D already has function and delegates,
> is there a point to functor ?

D is a multi-paradigm language that has operator overloading, so it pretty
much naturally ends up with functors whether it was specifically planned for
or not, though I'm not sure that they get used all that much. I think that
some folks do use them instead of delegates in some situations, because
delegates allocate closures to hold their state (copying the associated
stack onto GC-allocated memory). So, if you have code that you want or need
to be @nogc, delegates aren't going to work, whereas functors can. The
biggest reason that a lot of Phobos has trouble being used in @nogc code is
because of closures being allocated for lambdas (since lambdas are
frequently delegates), and if someone goes to the extra effort of using
functors instead of lambdas, they can avoid those allocations. But I think
that most folks don't worry about it and just use lambdas. It's the folks
that either actually need @nogc or are just paranoid about the GC that most
typically try to avoid such allocations - though I'm sure that we'd all love
it if the compiler could be a bit smarter about not allocating closures when
they're not actually needed (it's pretty conservative about it, because if
it ever doesn't allocate a closure when one was needed, then you have an
@safety bug).

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list