1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_NotNull_h
8 #define mozilla_NotNull_h
10 // It's often unclear if a particular pointer, be it raw (T*) or smart
11 // (RefPtr<T>, nsCOMPtr<T>, etc.) can be null. This leads to missing null
12 // checks (which can cause crashes) and unnecessary null checks (which clutter
15 // C++ has a built-in alternative that avoids these problems: references. This
16 // module defines another alternative, NotNull, which can be used in cases
17 // where references are not suitable.
19 // In the comments below we use the word "handle" to cover all varieties of
20 // pointers and references.
24 // References are always non-null. (You can do |T& r = *p;| where |p| is null,
25 // but that's undefined behaviour. C++ doesn't provide any built-in, ironclad
26 // guarantee of non-nullness.)
28 // A reference works well when you need a temporary handle to an existing
29 // single object, e.g. for passing a handle to a function, or as a local handle
30 // within another object. (In Rust parlance, this is a "borrow".)
32 // A reference is less appropriate in the following cases.
34 // - As a primary handle to an object. E.g. code such as this is possible but
35 // strange: |T& t = *new T(); ...; delete &t;|
37 // - As a handle to an array. It's common for |T*| to refer to either a single
38 // |T| or an array of |T|, but |T&| cannot refer to an array of |T| because
39 // you can't index off a reference (at least, not without first converting it
42 // - When the handle identity is meaningful, e.g. if you have a hashtable of
43 // handles, because you have to use |&| on the reference to convert it to a
46 // - Some people don't like using non-const references as function parameters,
47 // because it is not clear at the call site that the argument might be
50 // - When you need "smart" behaviour. E.g. we lack reference equivalents to
51 // RefPtr and nsCOMPtr.
53 // - When interfacing with code that uses pointers a lot, sometimes using a
54 // reference just feels like an odd fit.
56 // Furthermore, a reference is impossible in the following cases.
58 // - When the handle is rebound to another object. References don't allow this.
60 // - When the handle has type |void|. |void&| is not allowed.
62 // NotNull is an alternative that can be used in any of the above cases except
63 // for the last one, where the handle type is |void|. See below.
65 #include "mozilla/Assertions.h"
66 #include "mozilla/Move.h"
71 // NotNull can be used to wrap a "base" pointer (raw or smart) to indicate it
72 // is not null. Some examples:
75 // - NotNull<RefPtr<Event>>
76 // - NotNull<nsCOMPtr<Event>>
78 // NotNull has the following notable properties.
80 // - It has zero space overhead.
82 // - It must be initialized explicitly. There is no default initialization.
84 // - It auto-converts to the base pointer type.
86 // - It does not auto-convert from a base pointer. Implicit conversion from a
87 // less-constrained type (e.g. T*) to a more-constrained type (e.g.
88 // NotNull<T*>) is dangerous. Creation and assignment from a base pointer can
89 // only be done with WrapNotNull() or MakeNotNull<>(), which makes them
90 // impossible to overlook, both when writing and reading code.
92 // - When initialized (or assigned) it is checked, and if it is null we abort.
93 // This guarantees that it cannot be null.
95 // - |operator bool()| is deleted. This means you cannot check a NotNull in a
96 // boolean context, which eliminates the possibility of unnecessary null
99 // NotNull currently doesn't work with UniquePtr. See
100 // https://github.com/Microsoft/GSL/issues/89 for some discussion.
102 template <typename T
>
104 template <typename U
>
105 friend constexpr NotNull
<U
> WrapNotNull(U aBasePtr
);
106 template <typename U
, typename
... Args
>
107 friend constexpr NotNull
<U
> MakeNotNull(Args
&&... aArgs
);
111 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
112 template <typename U
>
113 constexpr explicit NotNull(U aBasePtr
) : mBasePtr(aBasePtr
) {}
116 // Disallow default construction.
119 // Construct/assign from another NotNull with a compatible base pointer type.
120 template <typename U
>
121 constexpr MOZ_IMPLICIT
NotNull(const NotNull
<U
>& aOther
)
122 : mBasePtr(aOther
.get()) {
123 static_assert(sizeof(T
) == sizeof(NotNull
<T
>),
124 "NotNull must have zero space overhead.");
125 static_assert(offsetof(NotNull
<T
>, mBasePtr
) == 0,
126 "mBasePtr must have zero offset.");
129 // Default copy/move construction and assignment.
130 NotNull(const NotNull
<T
>&) = default;
131 NotNull
<T
>& operator=(const NotNull
<T
>&) = default;
132 NotNull(NotNull
<T
>&&) = default;
133 NotNull
<T
>& operator=(NotNull
<T
>&&) = default;
135 // Disallow null checks, which are unnecessary for this type.
136 explicit operator bool() const = delete;
138 // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
139 // get a castable pointer.
140 constexpr const T
& get() const { return mBasePtr
; }
142 // Implicit conversion to a base pointer. Preferable to get().
143 constexpr operator const T
&() const { return get(); }
145 // Dereference operators.
146 constexpr const T
& operator->() const { return get(); }
147 constexpr decltype(*mBasePtr
) operator*() const { return *mBasePtr
; }
150 template <typename T
>
151 constexpr NotNull
<T
> WrapNotNull(const T aBasePtr
) {
152 NotNull
<T
> notNull(aBasePtr
);
153 MOZ_RELEASE_ASSERT(aBasePtr
);
159 // Extract the pointed-to type from a pointer type (be it raw or smart).
160 // The default implementation uses the dereferencing operator of the pointer
161 // type to find what it's pointing to.
162 template <typename Pointer
>
164 // Remove the reference that dereferencing operators may return.
165 using Type
= typename RemoveReference
<decltype(*DeclVal
<Pointer
>())>::Type
;
166 using NonConstType
= typename RemoveConst
<Type
>::Type
;
169 // Specializations for raw pointers.
170 // This is especially required because VS 2017 15.6 (March 2018) started
171 // rejecting the above `decltype(*DeclVal<Pointer>())` trick for raw pointers.
173 template <typename T
>
174 struct PointedTo
<T
*> {
176 using NonConstType
= T
;
179 template <typename T
>
180 struct PointedTo
<const T
*> {
181 using Type
= const T
;
182 using NonConstType
= T
;
185 } // namespace detail
187 // Allocate an object with infallible new, and wrap its pointer in NotNull.
188 // |MakeNotNull<Ptr<Ob>>(args...)| will run |new Ob(args...)|
189 // and return NotNull<Ptr<Ob>>.
190 template <typename T
, typename
... Args
>
191 constexpr NotNull
<T
> MakeNotNull(Args
&&... aArgs
) {
192 using Pointee
= typename
detail::PointedTo
<T
>::NonConstType
;
193 static_assert(!IsArray
<Pointee
>::value
,
194 "MakeNotNull cannot construct an array");
195 return NotNull
<T
>(new Pointee(std::forward
<Args
>(aArgs
)...));
198 // Compare two NotNulls.
199 template <typename T
, typename U
>
200 constexpr bool operator==(const NotNull
<T
>& aLhs
, const NotNull
<U
>& aRhs
) {
201 return aLhs
.get() == aRhs
.get();
203 template <typename T
, typename U
>
204 constexpr bool operator!=(const NotNull
<T
>& aLhs
, const NotNull
<U
>& aRhs
) {
205 return aLhs
.get() != aRhs
.get();
208 // Compare a NotNull to a base pointer.
209 template <typename T
, typename U
>
210 constexpr bool operator==(const NotNull
<T
>& aLhs
, const U
& aRhs
) {
211 return aLhs
.get() == aRhs
;
213 template <typename T
, typename U
>
214 constexpr bool operator!=(const NotNull
<T
>& aLhs
, const U
& aRhs
) {
215 return aLhs
.get() != aRhs
;
218 // Compare a base pointer to a NotNull.
219 template <typename T
, typename U
>
220 constexpr bool operator==(const T
& aLhs
, const NotNull
<U
>& aRhs
) {
221 return aLhs
== aRhs
.get();
223 template <typename T
, typename U
>
224 constexpr bool operator!=(const T
& aLhs
, const NotNull
<U
>& aRhs
) {
225 return aLhs
!= aRhs
.get();
228 // Disallow comparing a NotNull to a nullptr.
229 template <typename T
>
230 bool operator==(const NotNull
<T
>&, decltype(nullptr)) = delete;
231 template <typename T
>
232 bool operator!=(const NotNull
<T
>&, decltype(nullptr)) = delete;
234 // Disallow comparing a nullptr to a NotNull.
235 template <typename T
>
236 bool operator==(decltype(nullptr), const NotNull
<T
>&) = delete;
237 template <typename T
>
238 bool operator!=(decltype(nullptr), const NotNull
<T
>&) = delete;
240 } // namespace mozilla
242 #endif /* mozilla_NotNull_h */