this post was submitted on 08 Jul 2023
16 points (100.0% liked)

C++

1763 readers
1 users here now

The center for all discussion and news regarding C++.

Rules

founded 1 year ago
MODERATORS
 

Hey all, teaching myself CPP through a few books (and a little bit of CS in general through CS50) and hit a road block.

I understand what pointers are, and understand they’re a big part of programming. My question is why?

What do you use pointers for? Why is forwarding to a new memory address preferable to just changing the variable/replacing what’s already at the memory address or at a new one? Is it because new data could exceed the size of that address already allocated?

Thanks in advance!

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 4 points 1 year ago

You need pointers to implement low-level stuff or for example containers. Sometimes you really just need the memory address itself e.g. for MMIO. That said, much of the stuff is implemented for you by the standard library and you do not usually need to directly use the pointers. That might change in embedded space.

Shared ownedship is another part where (reference-counted) pointers are useful. std::shared_ptr is this. I would generally say that shared ownedship in itself is much harder to reason than non-shared, but there are situations where you really want shared ownership.

Pointers in general shouldn't be your go-to tool. They are easy to mess up with, and memory errors are annoying to debug. And in my experience people who are overconfident in their use are the ones writing the worst security holes and incomprehensible interfaces. (Though those overconfident people with their BS keep me in business, so there's that.)

All that said, I wouldn't even teach pointers and raw memory stuff in the C++ intro course if I didn't know it comes up so often in job interviews.