C++ Core Guidelines has been presented recently (congrats!) and I am concerned about gsl::not_null
type. As stated in I.12: Declare a pointer that must not be null as not_null
:
To help avoid dereferencing nullptr errors. To improve performance by avoiding redundant checks for nullptr.
...
By stating the intent in source, implementers and tools can provide better diagnostics, such as finding some classes of errors through static analysis, and perform optimizations, such as removing branches and null tests.
The intent is clear. However, we already have a language feature for that. Pointers that cannot be null are called references. And while references cannot be rebound once they are created, this problem is solved by std::reference_wrapper
.
The main difference between gsl::not_null
and std::reference_wrapper
I see in that the latter can be used only instead of pointers, while the former works on anything nullptr
-assignable (quote from F.17: Use a not_null to indicate that "null" is not a valid value):
not_null
is not just for built-in pointers. It works forarray_view
,string_view
,unique_ptr
,shared_ptr
, and other pointer-like types.
I imagine the feature comparison table like the following:
T&
:
- Cannot store
nullptr
? - Yes - Rebindable? - No
- Can be used instead of something other than pointers? - No
std::reference_wrapper<T>
:
- Cannot store
nullptr
? - Yes - Rebindable? - Yes
- Can be used instead of something other than pointers? - No
gsl::not_null<T*>
:
- Cannot store
nullptr
? - Yes - Rebindable? - Yes
- Can be used instead of something other than pointers? - Yes
Now here are the questions, finally:
- Is my understanding of differences between these concepts correct?
- Does that mean that
std::reference_wrapper
is now useless?
PS I created tags cpp-core-guidelines
and guideline-support-library
for this, I hope properly.
Can be used instead of something other that pointers?
- typo in there somewhere? – Hawkshawstd::reference_wrapper
andgsl::not_null
for that purpose. But we cannot use references orstd::reference_wrapper
instead of, say,std::shared_ptr
passed to a function. – Cougar