What is the difference between: Handle, Pointer and Reference

后端 未结 4 1181
醉梦人生
醉梦人生 2021-01-30 07:22

How does a handle differ from a pointer to an object and also why can\'t we have a reference to a reference?

4条回答
  •  渐次进展
    2021-01-30 07:59

    A handle is also sometimes called a "magic cookie". Its just a value of some opaque type that identifies an object. In some cases it's implemented as an actual pointer, so if you cast it to a pointer to the correct type, you can dereference it and work with whatever sort of thing it points at.

    In other cases, it'll be implemented as something other than a pointer -- for example, you might have a table of objects of that type, and the handle is really just an index into that table. Unless you know the base address of the table, you can't do much of anything with the index.

    C++ simply says that references to references aren't possible. There isn't much in the way of a "why" -- if they'd wanted to badly enough, they undoubtedly could have allowed it (as well as arrays of references, for that matter). The decision was made, however, that it was best to restrict references (a lot), so that's what they did.

提交回复
热议问题