Comment by Panzerschrek
4 days ago
> Never null: it always holds a value, except in the moved-from state
I am wondering why C++ can't implement "non-null" unique_ptr version in the same way? As I know, that the main argument against implementing it is, that it's can't be done, since move-out unique_ptr still can be null.
The C++ core guideline support library has it.
https://github.com/microsoft/GSL/blob/main/docs/headers.md#u...
What do you mean by move-out unique_ptr? That the not_null ptr type would ne null after it's been moved?
In that case that's just a plain usage error, same as how you could memset it to null.
I've been thinking about things like that a bit. I see a very useful and safe Rust pattern, and wonder if I can possibly implement it in C++. Mostly the answer is no, because C++ is too powerful.
I would love to proved wrong, but everything I can think of still leaves a footgun that's easy to trigger by accident, and thus negates the point of the solution.
I think the can't-reference-after-moved-from and objects-are-not-Copy-by-default are key to creating these types (at least enforced at compile time). And that would require major language changes, at least as big as the C++11 changes.
Static analysis is the answer for some of these questions.
While many of us that like C++, would wish for a different evolution process, some of this stuff can be enforced by static analysis tooling.
Just like despite being safer than C++, we still use Sonar, FindBugs, FxCop/Roslyn Analysers, go vet, rust clippy, one more reason to actually use Sonar, clang-tidy, PVS, MSVC analyse,... with languages like C and C++.
In some of these you can add your own rules even, even if not always that straightforward.
I think nothing prevents this, but this is just not the point of unique_ptr. unique_ptr is still ptr, so it consequently follows raw pointer semantics.