What is the difference between a C# Reference and a Pointer?

后端 未结 10 1818
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 21:45

I do not quite understand the difference between a C# reference and a pointer. They both point to a place in memory don\'t they? The only difference I can figure out is that

相关标签:
10条回答
  • 2020-11-28 22:25

    A reference is an "abstract" pointer: you can't do arithmetic with a reference and you can't play any low-level tricks with its value.

    0 讨论(0)
  • 2020-11-28 22:25

    A pointer can point to any byte in the address space of the application. A reference is tightly constrained and controlled and managed by the .NET environment.

    0 讨论(0)
  • 2020-11-28 22:28

    There is a slight, yet extremely important, distinction between a pointer and a reference. A pointer points to a place in memory while a reference points to an object in memory. Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at.

    Take for example the following code

    int* p1 = GetAPointer();
    

    This is type safe in the sense that GetAPointer must return a type compatible with int*. Yet there is still no guarantee that *p1 will actually point to an int. It could be a char, double or just a pointer into random memory.

    A reference however points to a specific object. Objects can be moved around in memory but the reference cannot be invalidated (unless you use unsafe code). References are much safer in this respect than pointers.

    string str = GetAString();
    

    In this case str has one of two state 1) it points to no object and hence is null or 2) it points to a valid string. That's it. The CLR guarantees this to be the case. It cannot and will not for a pointer.

    0 讨论(0)
  • 2020-11-28 22:30

    I think it's important for developers to understand the concept of a pointer—that is, to understand indirection. That doesn't mean they necessarily have to use pointers. It's also important to understand that the concept of a reference differs from the concept of pointer, although only subtly, but that the implementation of a reference almost always is a pointer.

    That is to say, a variable holding a reference is just a pointer-sized block of memory holding a pointer to the object. However, this variable cannot be used in the same way that a pointer variable can be used. In C# (and C, and C++, ...), a pointer can be indexed like an array, but a reference cannot. In C#, a reference is tracked by the garbage collector, a pointer cannot be. In C++, a pointer can be reassigned, a reference cannot. Syntactically and semantically, pointers and references are quite different, but mechanically, they're the same.

    0 讨论(0)
提交回复
热议问题