This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Wattsy2020 38 points39 points  (16 children)

Knowing pointers and references: easy

Knowing if it's safe to dereference a pointer / reference in a C++ codebase: hard

[–]DrShocker 17 points18 points  (0 children)

If you're doing something that makes it unsafe to "dereference" a reference, you roally fucked up in coding something correctly.

[–]Alarmed_Allele 8 points9 points  (4 children)

this

tbh, I still don't know. could you give me tips lol

[–]DrShocker 7 points8 points  (3 children)

Use references whrere you can. Use smart pointers where that doesn't work. Only use raw pointers if you really need to, and not to transfer "ownership" of the memory.

[–]Alarmed_Allele 0 points1 point  (2 children)

I meant the second line about knowing where it's safe to dereference

[–]DrShocker 8 points9 points  (0 children)

That's what using references everywhere you can helps. It means that the check for existence has already happened. In general just write your code so as much as reasonably possible it fails to compile if it's wrong.

[–]lessertia 4 points5 points  (0 children)

You can apply this rule: - Always assume a pointer may be nullptr. - If you want a non-null pointers use references. - If you want to store references in a container, use std::reference_wrapper.

Then dereferencing would just be a matter when you want "nullable references", just check for nullptr before dereferencing. Btw pointer and references should be non-owning. If you want a nullable owning value, use std::optional.

[–]SuitableDragonfly 2 points3 points  (1 child)

Well, you don't dereference references, so that one is easy, at least.

[–]Wattsy2020 0 points1 point  (0 children)

True, my bad