• Ethan@programming.dev
    link
    fedilink
    English
    arrow-up
    7
    arrow-down
    5
    ·
    edit-2
    7 months ago

    As someone whose first language was C, I plan to never use C++ for anything more than programming an Arduino precisely because of the multitude of pointer types. A pointer should just be a pointer. Having five hundred different flavors of pointers is confusing as fuck.

    • Redkey@programming.dev
      link
      fedilink
      arrow-up
      12
      ·
      7 months ago

      That was my first take as well, coming back to C++ in recent years after a long hiatus. But once I really got into it I realized that those pointer types still exist (conceptually) in C, but they’re undeclared and mostly unmanaged by the compiler. The little bit of automagic management that does happen is hidden from the programmer.

      I feel like most of the complex overhead in modern C++ is actually just explaining in extra detail about what you think is happening. Where a C compiler would make your code work in any way possible, which may or may not be what you intended, a C++ compiler will kick out errors and let you know where you got it wrong. I think it may be a bit like JavaScript vs TypeScript: the issues were always there, we just introduced mechanisms to point them out.

      You’re also mostly free to use those C-style pointers in C++. It’s just generally considered bad practice.

    • Traister101@lemmy.today
      link
      fedilink
      arrow-up
      4
      ·
      edit-2
      7 months ago

      Smart pointers model ownership. Instead of (maybe) a comment telling you if you have to free/delete a returned pointer this information is encoded into the type itself. But that’s not all, this special type even handles the whole deleting part once it goes away.

      Since they model ownership you should only use them when ownership should be expressed. Namely something that returns a pointer to a newly allocated thing should be a std::unique_ptr because the Callie has ownership of that memory. If they want to share it (multiple ownership of the object) there’s a cheap conversion to std::shared_ptr.

      How about a function that takes in an object cause it wants to look at it? Well that doesn’t have anything to do with ownership so make it a raw pointer, or better yet a reference to avoid nullability.

      What about when you’ve got a member function that wants to return a pointer to some memory the object owns? You guessed it baby raw pointer (or again reference if it’ll never be null).