0

I get that you need pointers for handling something that grows and shrinks dynamically. In instances where that isn't the case, to my understanding, you use pointers when: your object is too big to be stored on the stack, or when you would like a function to modify data outside of its scope (why not just use references here?). Is this line of thinking correct?

Other uses I can think of are for polymorphism and forward declarations. The other example people always give is pointer arithmetic and handling array indices, but then why not just use C++ iterators which just wrap pointers... Are there any other (common) cases? I used to think that pointers were useful as they allowed for objects to be passed around without the need for a full copy to be made, but surely move semantics allow you to accomplish that without the need for handling pointers?

Overall, I feel like I am using too many unnecessary pointers in my codebase and I would really appreciate it if someone could definitively clear things up.

  • 4
    In short: Almost never. You ain't gonna need them. You can always either use [standard containers](https://en.cppreference.com/w/cpp/container) or [smart pointers](https://en.cppreference.com/w/cpp/memory). – πάντα ῥεῖ Sep 03 '20 at 23:09
  • 2
    There are exceptions, such as writing to hardware devices. Some hardware devices are mapped to addresses. The way to access them is to load a pointer with the address of the hardware device, then write to the h/w device via the pointer. – Thomas Matthews Sep 03 '20 at 23:12
  • @ThomasMatthews: Although that's usually only the case in embedded systems or driver programming nowadays; this isn't the '80s, where game programmers interacted with the hardware directly (and when they screwed up, crashed the whole computer). – ShadowRanger Sep 03 '20 at 23:15
  • You should use *raw* pointers when there are no other solutions available (including redesigning the program). – Thomas Matthews Sep 04 '20 at 00:33
  • 1
    @πάνταῥεῖ Pointers are ok. Use them. Don't use OWNING raw pointers though. – Swordfish Sep 04 '20 at 00:44
  • You will find cases where raw, [non-owning](https://stackoverflow.com/questions/49024982/what-is-ownership-of-resources-or-pointers) pointers are the right solution. For example try to assign a class with a reference member. Pain in the . Of course then you gotta wonder, "Why do I have a reference member?" – user4581301 Sep 04 '20 at 00:45
  • @Swordfish We can agree to disagree. Can you tell at least a single situation (besides what _@Thomas Mathews_ mentioned) where you need to use them in c++? Even for non owning we are better off with `std::weak_ptr` or `std::shared_ptr`. – πάντα ῥεῖ Sep 04 '20 at 05:22
  • @user4581301 As I said above. Please tell t least a single one? What you said in the end: _"Why do you need to have a reference member?"_. – πάντα ῥεῖ Sep 04 '20 at 05:24

0 Answers0