Conversation

Yes, you're missing something. It clearly does absolutely nothing to prevent NULL dereferences or use-after-move so lets skip those. To use unique_ptr, you need to copy from it or get a reference. That reference isn't safe, and std::unique_ptr will still free with it active.
1
Why would you be using std::unique_ptr in the first place if you just want a value to copy around? That wouldn't make any sense. It's used to manage the lifetime of a dynamic allocation, where you are using it via references, not copying the contents out for every single use.
1
Similarly, for std::shared_ptr, you are still going to be using references to it, including mutable references, which are extremely dangerous in C++ since they can invalidate other references to the contents by changing the length of a container, a dynamic type, variant type, etc
1
Weak pointers also make things even more unsafe for similar reasons as the baseline with unique pointers and shared pointers. Same applies to types like std::string. You have automatic free at end of scope, even after you've taken references / string views. Fundamental issue.
1
And yet, with no get(), and only using the uniq_ptr directly, you avoid a whole class of problem, and you still convey the ownership information to the reader. You can still move ownership to other class. I can't see how it happen when using raw ptr only at the uniq_ptr scope.
2
In fact I never ever used uniq_ptr::get() directly. I only used uptr->type. (shared_ptr has its issues, but its still better than C ptr generally speaking, rust gives a better scope compile time analysis, but C++ gives you some of that. It's not as good, but better than 0 of C)
1
C++ doesn't provide any compile-time safety from use-after-free, since references have no safety and are even implicit. Where are you even using std::unique_ptr? I don't find that there are many use cases for unique pointers other than implementing tree data structures.
1
Having that free as automatic / implicit certainly makes it harder to leak memory, but in the real world I don't think it improves safety. Many of the memory corruption bugs that I find are due to use-after-free largely missed due to implicit C++ destruction at the end of scope.
1
Show replies