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

后端 未结 10 1862
隐瞒了意图╮
隐瞒了意图╮ 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:12

    A major difference between a reference and a pointer is that a pointer is a collection of bits whose content only matters when it is actively being used as a pointer, while a reference encapsulates not only a set of bits, but also some metadata which keeps the underlying framework informed of its existence. If a pointer exists to some object in memory, and that object is deleted but the pointer is not erased, the pointer's continued existence won't cause any harm unless or until an attempt is made to access the memory to which it points. If no attempt is made to use the pointer, nothing will care about its existence. By contrast, reference-based frameworks like .NET or the JVM require that it always be possible for the system to identify every object reference in existence, and every object reference in existence must always either be null or else identify an object of its proper type.

    Note that each object reference actually encapsulates two kinds of information: (1) the field contents of the object it identifies, and (2) the set of other references to the same object. Although there isn't any mechanism by which the system can quickly identify all the references that exist to an object, the set of other references that exist to an object may often be the most important thing encapsulated by a reference (this is especially true when things of type Object are used as things like lock tokens). Although the system keeps a few bits of data for each object for use in GetHashCode, objects have no real identity beyond the set of references that exist to them. If X holds the only extant reference to an object, replacing X with a reference to a new object with the same field contents will have no identifiable effect except to change the bits returned by GetHashCode(), and even that effect isn't guaranteed.

提交回复
热议问题