How are delegates in C# better than function pointers in C/C++?

后端 未结 4 891
心在旅途
心在旅途 2020-12-17 15:46

The delegates in C# offer similar functionality as function pointers in C. I heard someone saying \"C# delegates are actually better than function pointers in C\". How come?

4条回答
  •  囚心锁ツ
    2020-12-17 16:31

    Many people refer to C# delegates as more "type-safe" than C++ function pointers and I really find it misleading. In reality they are no more type-safe that C++'s function pointers are. An example C++ code (compiled by MSVS 2005 SP1):

    typedef int (*pfn) (int);
    
    int f (int) {
       return 0;
    }
    
    double d (int) {
       return 1;
    }
    
    int main()
    {
       pfn p=f; // OK
       p=d; // error C2440: '=' : cannot convert from 'double (__cdecl *)(int)' to 'pfn'
       p=(pfn)d;
    }
    

    So as is seen from the example above unless one uses "dirty hacks" to "shut up" the compiler the type mismatch is easily detected and the compiler's message is easy to understand. So that is type-safety as I understand it.

    Regarding the "boundness" of the member function pointers. Indeed, in C++ pointer-to-member is not bound, the member function pointer has to be applied to a type variable that matches the member pointer's signature. An example:

    class A {
    public:
    
       int f (int) {
          return 2;
       }
    
    };
    
    typedef int (A::*pmfn) (int);
    
    int main()
    {
       pmfn p=&(A::f);
       // Now call it.
       A *a=new A;
       (a->*p)(0); // Calls A::f
    }
    

    Again, everything is perfectly type safe.

提交回复
热议问题