To what extent is it acceptable to think of C++ pointers as memory addresses?

后端 未结 12 1126
难免孤独
难免孤独 2020-12-10 10:18

When you learn C++, or at least when I learned it through C++ Primer, pointers were termed the \"memory addresses\" of the elements they point to. I\'m wondering to

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 10:44

    Not at all.

    C++ is an abstraction over the code that your computer will perform. We see this abstraction leak in a few places (class member references requiring storage, for example) but in general you will be better off if you code to the abstraction and nothing else.

    Pointers are pointers. They point to things. Will they be implemented as memory addresses in reality? Maybe. They could also be optimised out, or (in the case of e.g. pointers-to-members) they could be somewhat more complex than a simple numeric address.

    When you start thinking of pointers as integers that map to addresses in memory, you begin to forget for example that it's undefined to hold a pointer to an object that doesn't exist (you can't just increment and decrement a pointer willy nilly to any memory address you like).

提交回复
热议问题