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.
67 #include <type_traits>
70 #include "mozilla/Assertions.h"
80 explicit CopyablePtr(U aPtr
) : mPtr
{std::move(aPtr
)} {}
87 // NotNull can be used to wrap a "base" pointer (raw or smart) to indicate it
88 // is not null. Some examples:
91 // - NotNull<RefPtr<Event>>
92 // - NotNull<nsCOMPtr<Event>>
94 // NotNull has the following notable properties.
96 // - It has zero space overhead.
98 // - It must be initialized explicitly. There is no default initialization.
100 // - It auto-converts to the base pointer type.
102 // - It does not auto-convert from a base pointer. Implicit conversion from a
103 // less-constrained type (e.g. T*) to a more-constrained type (e.g.
104 // NotNull<T*>) is dangerous. Creation and assignment from a base pointer can
105 // only be done with WrapNotNull() or MakeNotNull<>(), which makes them
106 // impossible to overlook, both when writing and reading code.
108 // - When initialized (or assigned) it is checked, and if it is null we abort.
109 // This guarantees that it cannot be null.
111 // - |operator bool()| is deleted. This means you cannot check a NotNull in a
112 // boolean context, which eliminates the possibility of unnecessary null
115 // NotNull currently doesn't work with UniquePtr. See
116 // https://github.com/Microsoft/GSL/issues/89 for some discussion.
118 template <typename T
>
120 template <typename U
>
121 friend constexpr NotNull
<U
> WrapNotNull(U aBasePtr
);
122 template <typename U
>
123 friend constexpr NotNull
<U
> WrapNotNullUnchecked(U aBasePtr
);
124 template <typename U
, typename
... Args
>
125 friend constexpr NotNull
<U
> MakeNotNull(Args
&&... aArgs
);
126 template <typename U
>
127 friend class NotNull
;
129 detail::CopyablePtr
<T
> mBasePtr
;
131 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
132 template <typename U
>
133 constexpr explicit NotNull(U aBasePtr
) : mBasePtr(T
{std::move(aBasePtr
)}) {
134 static_assert(sizeof(T
) == sizeof(NotNull
<T
>),
135 "NotNull must have zero space overhead.");
136 static_assert(offsetof(NotNull
<T
>, mBasePtr
) == 0,
137 "mBasePtr must have zero offset.");
141 // Disallow default construction.
144 // Construct/assign from another NotNull with a compatible base pointer type.
145 template <typename U
>
146 constexpr MOZ_IMPLICIT
NotNull(const NotNull
<U
>& aOther
)
147 : mBasePtr(aOther
.mBasePtr
) {}
149 template <typename U
>
150 constexpr MOZ_IMPLICIT
NotNull(MovingNotNull
<U
>&& aOther
)
151 : mBasePtr(std::move(aOther
).unwrapBasePtr()) {}
153 // Disallow null checks, which are unnecessary for this type.
154 explicit operator bool() const = delete;
156 // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
157 // get a castable pointer.
158 constexpr const T
& get() const { return mBasePtr
.mPtr
; }
160 // Implicit conversion to a base pointer. Preferable to get().
161 constexpr operator const T
&() const { return get(); }
163 // Dereference operators.
164 constexpr auto* operator->() const MOZ_NONNULL_RETURN
{
165 return mBasePtr
.mPtr
.operator->();
167 constexpr decltype(*mBasePtr
.mPtr
) operator*() const {
168 return *mBasePtr
.mPtr
;
171 // NotNull can be copied, but not moved. Moving a NotNull with a smart base
172 // pointer would leave a nullptr NotNull behind. The move operations must not
173 // be explicitly deleted though, since that would cause overload resolution to
174 // fail in situations where a copy is possible.
175 NotNull(const NotNull
&) = default;
176 NotNull
& operator=(const NotNull
&) = default;
179 // Specialization for T* to allow adding MOZ_NONNULL_RETURN attributes.
180 template <typename T
>
182 template <typename U
>
183 friend constexpr NotNull
<U
> WrapNotNull(U aBasePtr
);
184 template <typename U
>
185 friend constexpr NotNull
<U
*> WrapNotNullUnchecked(U
* aBasePtr
);
186 template <typename U
, typename
... Args
>
187 friend constexpr NotNull
<U
> MakeNotNull(Args
&&... aArgs
);
188 template <typename U
>
189 friend class NotNull
;
193 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
194 template <typename U
>
195 constexpr explicit NotNull(U
* aBasePtr
) : mBasePtr(aBasePtr
) {}
198 // Disallow default construction.
201 // Construct/assign from another NotNull with a compatible base pointer type.
202 template <typename U
>
203 constexpr MOZ_IMPLICIT
NotNull(const NotNull
<U
>& aOther
)
204 : mBasePtr(aOther
.get()) {
205 static_assert(sizeof(T
*) == sizeof(NotNull
<T
*>),
206 "NotNull must have zero space overhead.");
207 static_assert(offsetof(NotNull
<T
*>, mBasePtr
) == 0,
208 "mBasePtr must have zero offset.");
211 template <typename U
>
212 constexpr MOZ_IMPLICIT
NotNull(MovingNotNull
<U
>&& aOther
)
213 : mBasePtr(NotNull
{std::move(aOther
)}) {}
215 // Disallow null checks, which are unnecessary for this type.
216 explicit operator bool() const = delete;
218 // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
219 // get a castable pointer.
220 constexpr T
* get() const MOZ_NONNULL_RETURN
{ return mBasePtr
; }
222 // Implicit conversion to a base pointer. Preferable to get().
223 constexpr operator T
*() const MOZ_NONNULL_RETURN
{ return get(); }
225 // Dereference operators.
226 constexpr T
* operator->() const MOZ_NONNULL_RETURN
{ return get(); }
227 constexpr T
& operator*() const { return *mBasePtr
; }
230 template <typename T
>
231 constexpr NotNull
<T
> WrapNotNull(T aBasePtr
) {
232 MOZ_RELEASE_ASSERT(aBasePtr
);
233 return NotNull
<T
>{std::move(aBasePtr
)};
236 // WrapNotNullUnchecked should only be used in situations, where it is
237 // statically known that aBasePtr is non-null, and redundant release assertions
238 // should be avoided. It is only defined for raw base pointers, since it is only
239 // needed for those right now. There is no fundamental reason not to allow
240 // arbitrary base pointers here.
241 template <typename T
>
242 constexpr NotNull
<T
> WrapNotNullUnchecked(T aBasePtr
) {
243 return NotNull
<T
>{std::move(aBasePtr
)};
246 template <typename T
>
248 constexpr NotNull
<T
*> WrapNotNullUnchecked(T
* const aBasePtr
) {
249 #if defined(__clang__)
250 # pragma clang diagnostic push
251 # pragma clang diagnostic ignored "-Wpointer-bool-conversion"
252 #elif defined(__GNUC__)
253 # pragma GCC diagnostic push
254 # pragma GCC diagnostic ignored "-Wnonnull-compare"
256 MOZ_ASSERT(aBasePtr
);
257 #if defined(__clang__)
258 # pragma clang diagnostic pop
259 #elif defined(__GNUC__)
260 # pragma GCC diagnostic pop
262 return NotNull
<T
*>{aBasePtr
};
265 // A variant of NotNull that can be used as a return value or parameter type and
266 // moved into both NotNull and non-NotNull targets. This is not possible with
267 // NotNull, as it is not movable. MovingNotNull can therefore not guarantee it
268 // is always non-nullptr, but it can't be dereferenced, and there are debug
269 // assertions that ensure it is only moved once.
270 template <typename T
>
271 class MOZ_NON_AUTOABLE MovingNotNull
{
272 template <typename U
>
273 friend constexpr MovingNotNull
<U
> WrapMovingNotNullUnchecked(U aBasePtr
);
277 bool mConsumed
= false;
280 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
281 template <typename U
>
282 constexpr explicit MovingNotNull(U aBasePtr
) : mBasePtr
{std::move(aBasePtr
)} {
284 static_assert(sizeof(T
) == sizeof(MovingNotNull
<T
>),
285 "NotNull must have zero space overhead.");
287 static_assert(offsetof(MovingNotNull
<T
>, mBasePtr
) == 0,
288 "mBasePtr must have zero offset.");
292 MovingNotNull() = delete;
294 MOZ_IMPLICIT
MovingNotNull(const NotNull
<T
>& aSrc
) : mBasePtr(aSrc
) {}
296 template <typename U
>
297 MOZ_IMPLICIT
MovingNotNull(const NotNull
<U
>& aSrc
) : mBasePtr(aSrc
) {}
299 template <typename U
>
300 MOZ_IMPLICIT
MovingNotNull(MovingNotNull
<U
>&& aSrc
)
301 : mBasePtr(std::move(aSrc
).unwrapBasePtr()) {}
303 MOZ_IMPLICIT
operator T() && { return std::move(*this).unwrapBasePtr(); }
305 MOZ_IMPLICIT
operator NotNull
<T
>() && { return std::move(*this).unwrap(); }
307 NotNull
<T
> unwrap() && {
308 return WrapNotNullUnchecked(std::move(*this).unwrapBasePtr());
311 T
unwrapBasePtr() && {
313 MOZ_ASSERT(!mConsumed
);
316 return std::move(mBasePtr
);
319 MovingNotNull(MovingNotNull
&&) = default;
320 MovingNotNull
& operator=(MovingNotNull
&&) = default;
323 template <typename T
>
324 constexpr MovingNotNull
<T
> WrapMovingNotNullUnchecked(T aBasePtr
) {
325 return MovingNotNull
<T
>{std::move(aBasePtr
)};
328 template <typename T
>
329 constexpr MovingNotNull
<T
> WrapMovingNotNull(T aBasePtr
) {
330 MOZ_RELEASE_ASSERT(aBasePtr
);
331 return WrapMovingNotNullUnchecked(std::move(aBasePtr
));
336 // Extract the pointed-to type from a pointer type (be it raw or smart).
337 // The default implementation uses the dereferencing operator of the pointer
338 // type to find what it's pointing to.
339 template <typename Pointer
>
341 // Remove the reference that dereferencing operators may return.
342 using Type
= std::remove_reference_t
<decltype(*std::declval
<Pointer
>())>;
343 using NonConstType
= std::remove_const_t
<Type
>;
346 // Specializations for raw pointers.
347 // This is especially required because VS 2017 15.6 (March 2018) started
348 // rejecting the above `decltype(*std::declval<Pointer>())` trick for raw
351 template <typename T
>
352 struct PointedTo
<T
*> {
354 using NonConstType
= T
;
357 template <typename T
>
358 struct PointedTo
<const T
*> {
359 using Type
= const T
;
360 using NonConstType
= T
;
363 } // namespace detail
365 // Allocate an object with infallible new, and wrap its pointer in NotNull.
366 // |MakeNotNull<Ptr<Ob>>(args...)| will run |new Ob(args...)|
367 // and return NotNull<Ptr<Ob>>.
368 template <typename T
, typename
... Args
>
369 constexpr NotNull
<T
> MakeNotNull(Args
&&... aArgs
) {
370 using Pointee
= typename
detail::PointedTo
<T
>::NonConstType
;
371 static_assert(!std::is_array_v
<Pointee
>,
372 "MakeNotNull cannot construct an array");
373 return NotNull
<T
>(new Pointee(std::forward
<Args
>(aArgs
)...));
376 // Compare two NotNulls.
377 template <typename T
, typename U
>
378 constexpr bool operator==(const NotNull
<T
>& aLhs
, const NotNull
<U
>& aRhs
) {
379 return aLhs
.get() == aRhs
.get();
381 template <typename T
, typename U
>
382 constexpr bool operator!=(const NotNull
<T
>& aLhs
, const NotNull
<U
>& aRhs
) {
383 return aLhs
.get() != aRhs
.get();
386 // Compare a NotNull to a base pointer.
387 template <typename T
, typename U
>
388 constexpr bool operator==(const NotNull
<T
>& aLhs
, const U
& aRhs
) {
389 return aLhs
.get() == aRhs
;
391 template <typename T
, typename U
>
392 constexpr bool operator!=(const NotNull
<T
>& aLhs
, const U
& aRhs
) {
393 return aLhs
.get() != aRhs
;
396 // Compare a base pointer to a NotNull.
397 template <typename T
, typename U
>
398 constexpr bool operator==(const T
& aLhs
, const NotNull
<U
>& aRhs
) {
399 return aLhs
== aRhs
.get();
401 template <typename T
, typename U
>
402 constexpr bool operator!=(const T
& aLhs
, const NotNull
<U
>& aRhs
) {
403 return aLhs
!= aRhs
.get();
406 // Disallow comparing a NotNull to a nullptr.
407 template <typename T
>
408 bool operator==(const NotNull
<T
>&, decltype(nullptr)) = delete;
409 template <typename T
>
410 bool operator!=(const NotNull
<T
>&, decltype(nullptr)) = delete;
412 // Disallow comparing a nullptr to a NotNull.
413 template <typename T
>
414 bool operator==(decltype(nullptr), const NotNull
<T
>&) = delete;
415 template <typename T
>
416 bool operator!=(decltype(nullptr), const NotNull
<T
>&) = delete;
418 } // namespace mozilla
420 #endif /* mozilla_NotNull_h */