Except that unique_ptr is still completely unsafe due to use-after-free via references, use-after-move and null pointer dereferences. Avoiding memory leaks is a separate thing from memory safety. Implicit destruction in a language without memory safety encourages use-after-free.
Conversation
It's a lot different in Rust where the language enforces memory safety and prevents dangling references (including iterators, string views, etc. and anything else made out of lightweight references), use-after-free, data races and so on. Fancy C++ encourages having these issues.
1
I'm not saying that they're bad language features. It's awesome having pervasive use of lightweight references, iterators, string views, etc. but when you use something like iterators or en.cppreference.com/w/cpp/string/b in C++, it's an extreme danger. One tiny mistake is an RCE vuln.
1
Iterators are evil, I perfectly agree. I don't see how can uniq_ptr cause those memory errors more than a raw pointer.
None of what you said can happen if you don't let the raw pointer escape, or am I missing something?
1
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
The std::shared_ptr design also encourages data races, since it goes out of the way to provide thread safety with extremely inefficient atomic reference counting, but doesn't provide a locking mechanism paired with it.
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
No, you don't avoid the problems by avoiding get(). The language doesn't stop you from dereferencing an uninitialized or moved std::unique_ptr and references can and will commonly be taken without needing the get() method. References are completely unsafe, not just raw pointers.

