Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I handle an event with a lambda in C++/CX?

Is it possible to handle an event with a lambda in C++/CX? As an example, what would be the best way to convert this snippet of code from C# into C++/CX?

this.animation.Completed += (s, e) =>
{
   animation.Begin();
};
like image 848
Andrew Garrison Avatar asked Sep 18 '12 14:09

Andrew Garrison


2 Answers

Here's what I ended up doing.

animation->Completed += ref new EventHandler<Object^>([this](Object^, Object^)
{
   animtion->Begin();
});
like image 28
Andrew Garrison Avatar answered Sep 20 '22 14:09

Andrew Garrison


Yes, that's the correct syntax. However, we recommend that you use a function handler instead of a lambda because a lambda can introduce a circular references and prevent memory from being freed.

http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh755799.aspx

In general, it's better to use a named function, rather than a lambda, for an event handler unless you take great care to avoid circular references. A named function captures the "this" pointer by weak reference, whereas a lambda captures it by strong reference and creates a circular reference. For more information, see Weak references and breaking cycles (C++/CX).

like image 80
Thomas Petchel Avatar answered Sep 21 '22 14:09

Thomas Petchel