The C++ standard library lacks a type to denote a smart pointer is not null. For raw pointer there is std::reference_wrapper, or a plain reference.
Other third-party libraries provide such a type, such as gsl::strict_not_null. However, GSL’s not_null requires copies and disallows moves of the underlying smart pointer, which is expensive and makes is impossible to use on a std::unique_ptr in real code.
Fix all issues by adding util::NotNull<SmartPtrType>, which documents (and checks) that the inner pointer is never null. Only when the inner pointer was moved, it becomes null, even inside NotNull. However, this is fine, because with clang-tidy use-after-free is forbidden, so it will never be possible to observe the silent inner nullptr.
This type can be used when passing never-null smart pointers between functions. It removes the need to Assert() the pointer before dereference. For example, in a getter function:
0util::NotNull<std::unique_ptr<Stats>> GetStats()
1{
2 return util::NotNull{std::make_unique<Stats>()};
3}
4
5int main()
6{
7 auto stats{GetStats()};
8 stats->foo; // This can never lead to a nullptr deref
9 // Assert(stats)->foo; // This is redundant and won't compile
10}