I’ve got such a class and delegate in C#:
public delegate void Super();
public class Event
{
public event Super activate ;
public void act()
{
if (activate != null)
activate();
}
}
I need to rewrite it in C++/CLI. But I’ve got an error – usage requires Event::activate to be data member
public delegate void Super();
public ref class Event
{
public:
event Super ^activate;
void act()
{
if (activate!=nullptr)
activate();
}
};
Is it problem in activate() call?
IIRC, in C++/CLI you don’t need the null test, the compiler will insert it for you. Just call
MSDN confirms this:
This is a very good thing, because C# encourages a race condition (the code you posted has one). The C++/CLI compiler won’t re-read the backing field between the null check and invocation, so it is thread-safe without additional effort. The correct C# version, which is equivalent to what the C++/CLI compiler generates, is: