I have a small question.
is function Pointer
in C++ similar in behavior with delegate
in C# ?
I have a small question. is |
|||
show 2 more comments |
Yes, they're similar. But function pointer in C++ cannot point to an instance method of class, while delegate in C# can. |
|||||||||||||||||||
|
Essentially, yes, but delegates are much richer. A function pointer is just a pointer to the memory where a function resides. A delegate is a class that wraps a function pointer along with other information. Because basically everything in C# is a class, delegates can point to methods on a class. In C++ this is a real pain because C++ functions use a special calling convention to call class methods, and the function pointer itself doesn't store a pointer to an object (you have to maintain that separately). Delegates can also be chained together and have more type flexibility than C++ function pointers. See Covariance and Contravariance in Delegates |
|||||
|
Well yes, C#'s delegate is a class type which handles a function pointer. And a function pointer is just a 32bit or 64bit unsigned integer which points to the specific location in memory that the function in question resides. In C++ you just have a raw, unmanaged function pointer. |
|||
|
A .NET delegate can have state -- i.e. you can create a delegate to an object's instance method and have
Function pointers have identical usage to delegates when they point to a non-member function. One could say they're actually better than delegates for this, because they're lighter weight (no allocations needed). However, function pointers have no state. This makes them much different when using them with member functions --
In C++ we also have "functors" -- objects which can have state and you can call like a function. This is the most used replacement for delegates when calling templated functions. But a functor is just a type concept, not an actual type:
A more apt comparison for exact duplication of a .NET delegate's functionality might be C++'s
|
||||
|
"Delegates are like C++ function pointers but are type safe."
– Jonathon Reinhart Jul 11 at 4:32function Pointer
, I remembered what I know in C# and especially delegate . – Lion King Jul 11 at 4:38typedef
!) – Jonathon Reinhart Jul 11 at 4:39