Are ref and out in C# the same a pointers in C++?

后端 未结 7 532
挽巷
挽巷 2021-01-05 04:00

I just made a Swap routine in C# like this:

static void Swap(ref int x, ref int y)
{
    int temp = x;
    x = y;
    y = temp;
}

It does t

7条回答
  •  长情又很酷
    2021-01-05 04:27

    While comparisons are in the eye of the beholder...I say no. 'ref' changes the calling convention but not the type of the parameters. In your C++ example, d1 and d2 are of type int*. In C# they are still Int32's, they just happen to be passed by reference instead of by value.

    By the way, your C++ code doesn't really swap its inputs in the traditional sense. Generalizing it like so:

    template
    void swap(T *d1, T *d2)
    {
        T temp = *d1;
        *d1 = *d2;
        *d2 = temp;
    }
    

    ...won't work unless all types T have copy constructors, and even then will be much more inefficient than swapping pointers.

提交回复
热议问题