Why don't some languages allow declaration of pointers?

前端 未结 7 1636
半阙折子戏
半阙折子戏 2020-12-31 05:41

I\'m programming in C++ right now, and I love using pointers. But it seems that other, newer languages like Java, C#, and Python don\'t allow you to explicitly declare point

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 06:06

    A true "pointer" has two characteristics.

    • It holds the address of another object (or primitive)
      • and exposes the numeric nature of that address so you can do arithmetic.

    Typically the arithmetic operations defined for pointers are:

    1. Adding an integer to a pointer into an array, which returns the address of another element.
    2. Subtracting two pointers into the same array, which returns the number of elements in-between (inclusive of one end).
    3. Comparing two pointers into the same array, which indicates which element is closer to the head of the array.

    Managed languages generally lead you down the road of "references" instead of pointers. A reference also holds the address of another object (or primitive), but arithmetic is disallowed.

    Among other things, this means you can't use pointer arithmetic to walk off the end of an array and treat some other data using the wrong type. The other way of forming an invalid pointer is taken care of in such environments by using garbage collection.

    Together this ensures type-safety, but at a terrible loss of generality.

提交回复
热议问题