简体   繁体   中英

Delegates in C# and fnc pointers in C++

I'm trying to familiarize myself with delegates and on http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx , I'm reading:

"Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure."

a mean, I do have C++ background, and somewhat cannot see how to understand the word "unlike" there. What do they mean by delegates are object-oriented and C++ fnc pointers are not? Same for type safe, and secure.

Anyone could show few examples and contra-examples?

Thanks.

A delegate does quite a bit more than a function pointer. It not only stores the function address, it also stores a reference to the target object. Unlike a C++ method pointer. So it is simple to use to call an instance method. That takes care of the "object-oriented" claim.

A bit down-hill from there, but type safety is ensured by the compiler verifying that the function signature exactly matches the delegate type when you assign the delegate. Which is no different in C++ but there's no way to cast a mismatch away. Another possible security aspect is that the object reference held by the delegate object is visible to the garbage collector. So you can never call an instance method on a deleted object.

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