简体   繁体   中英

Rewrite this line in C++/CLI

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

activate();

MSDN confirms this:

The following code example demonstrates the logic used to generate the raise method of a trivial event: If the event has one or more subscribers, calling the raise method implicitly or explicitly calls the delegate. If the delegate's return type is not void and if there are zero event subscribers, the raise method returns the default value for the delegate type. If there are no event subscribers, calling the raise method simply returns and no exception is raised. If the delegate return type is not void , the delegate type is returned.

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:

var activate_copy = activate;
if (activate_copy != null) 
    activate_copy();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM