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::forward
<U
>(aPtr
)} {}
83 explicit CopyablePtr(CopyablePtr
<U
> aPtr
) : mPtr
{std::move(aPtr
.mPtr
)} {}
90 // NotNull can be used to wrap a "base" pointer (raw or smart) to indicate it
91 // is not null. Some examples:
94 // - NotNull<RefPtr<Event>>
95 // - NotNull<nsCOMPtr<Event>>
96 // - NotNull<UniquePtr<Pointee>>
98 // NotNull has the following notable properties.
100 // - It has zero space overhead.
102 // - It must be initialized explicitly. There is no default initialization.
104 // - It auto-converts to the base pointer type.
106 // - It does not auto-convert from a base pointer. Implicit conversion from a
107 // less-constrained type (e.g. T*) to a more-constrained type (e.g.
108 // NotNull<T*>) is dangerous. Creation and assignment from a base pointer can
109 // only be done with WrapNotNull() or MakeNotNull<>(), which makes them
110 // impossible to overlook, both when writing and reading code.
112 // - When initialized (or assigned) it is checked, and if it is null we abort.
113 // This guarantees that it cannot be null.
115 // - |operator bool()| is deleted. This means you cannot check a NotNull in a
116 // boolean context, which eliminates the possibility of unnecessary null
119 // - It is not movable, but copyable if the base pointer type is copyable. It
120 // may be used together with MovingNotNull to avoid unnecessary copies or when
121 // the base pointer type is not copyable (such as UniquePtr<T>).
123 template <typename T
>
125 template <typename U
>
126 friend constexpr NotNull
<U
> WrapNotNull(U aBasePtr
);
127 template <typename U
>
128 friend constexpr NotNull
<U
> WrapNotNullUnchecked(U aBasePtr
);
129 template <typename U
, typename
... Args
>
130 friend constexpr NotNull
<U
> MakeNotNull(Args
&&... aArgs
);
131 template <typename U
>
132 friend class NotNull
;
134 detail::CopyablePtr
<T
> mBasePtr
;
136 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
137 template <typename U
>
138 constexpr explicit NotNull(U aBasePtr
) : mBasePtr(T
{std::move(aBasePtr
)}) {
139 static_assert(sizeof(T
) == sizeof(NotNull
<T
>),
140 "NotNull must have zero space overhead.");
141 static_assert(offsetof(NotNull
<T
>, mBasePtr
) == 0,
142 "mBasePtr must have zero offset.");
146 // Disallow default construction.
149 // Construct/assign from another NotNull with a compatible base pointer type.
150 template <typename U
>
151 constexpr MOZ_IMPLICIT
NotNull(const NotNull
<U
>& aOther
)
152 : mBasePtr(aOther
.mBasePtr
) {}
154 template <typename U
>
155 constexpr MOZ_IMPLICIT
NotNull(MovingNotNull
<U
>&& aOther
)
156 : mBasePtr(std::move(aOther
).unwrapBasePtr()) {}
158 // Disallow null checks, which are unnecessary for this type.
159 explicit operator bool() const = delete;
161 // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
162 // get a castable pointer.
163 constexpr const T
& get() const { return mBasePtr
.mPtr
; }
165 // Implicit conversion to a base pointer. Preferable to get().
166 constexpr operator const T
&() const { return get(); }
168 // Dereference operators.
169 constexpr auto* operator->() const MOZ_NONNULL_RETURN
{
170 return mBasePtr
.mPtr
.operator->();
172 constexpr decltype(*mBasePtr
.mPtr
) operator*() const {
173 return *mBasePtr
.mPtr
;
176 // NotNull can be copied, but not moved. Moving a NotNull with a smart base
177 // pointer would leave a nullptr NotNull behind. The move operations must not
178 // be explicitly deleted though, since that would cause overload resolution to
179 // fail in situations where a copy is possible.
180 NotNull(const NotNull
&) = default;
181 NotNull
& operator=(const NotNull
&) = default;
184 // Specialization for T* to allow adding MOZ_NONNULL_RETURN attributes.
185 template <typename T
>
187 template <typename U
>
188 friend constexpr NotNull
<U
> WrapNotNull(U aBasePtr
);
189 template <typename U
>
190 friend constexpr NotNull
<U
*> WrapNotNullUnchecked(U
* aBasePtr
);
191 template <typename U
, typename
... Args
>
192 friend constexpr NotNull
<U
> MakeNotNull(Args
&&... aArgs
);
193 template <typename U
>
194 friend class NotNull
;
198 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
199 template <typename U
>
200 constexpr explicit NotNull(U
* aBasePtr
) : mBasePtr(aBasePtr
) {}
203 // Disallow default construction.
206 // Construct/assign from another NotNull with a compatible base pointer type.
207 template <typename U
>
208 constexpr MOZ_IMPLICIT
NotNull(const NotNull
<U
>& aOther
)
209 : mBasePtr(aOther
.get()) {
210 static_assert(sizeof(T
*) == sizeof(NotNull
<T
*>),
211 "NotNull must have zero space overhead.");
212 static_assert(offsetof(NotNull
<T
*>, mBasePtr
) == 0,
213 "mBasePtr must have zero offset.");
216 template <typename U
>
217 constexpr MOZ_IMPLICIT
NotNull(MovingNotNull
<U
>&& aOther
)
218 : mBasePtr(NotNull
{std::move(aOther
)}) {}
220 // Disallow null checks, which are unnecessary for this type.
221 explicit operator bool() const = delete;
223 // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
224 // get a castable pointer.
225 constexpr T
* get() const MOZ_NONNULL_RETURN
{ return mBasePtr
; }
227 // Implicit conversion to a base pointer. Preferable to get().
228 constexpr operator T
*() const MOZ_NONNULL_RETURN
{ return get(); }
230 // Dereference operators.
231 constexpr T
* operator->() const MOZ_NONNULL_RETURN
{ return get(); }
232 constexpr T
& operator*() const { return *mBasePtr
; }
235 template <typename T
>
236 constexpr NotNull
<T
> WrapNotNull(T aBasePtr
) {
237 MOZ_RELEASE_ASSERT(aBasePtr
);
238 return NotNull
<T
>{std::move(aBasePtr
)};
241 // WrapNotNullUnchecked should only be used in situations, where it is
242 // statically known that aBasePtr is non-null, and redundant release assertions
243 // should be avoided. It is only defined for raw base pointers, since it is only
244 // needed for those right now. There is no fundamental reason not to allow
245 // arbitrary base pointers here.
246 template <typename T
>
247 constexpr NotNull
<T
> WrapNotNullUnchecked(T aBasePtr
) {
248 return NotNull
<T
>{std::move(aBasePtr
)};
251 template <typename T
>
253 constexpr NotNull
<T
*> WrapNotNullUnchecked(T
* const aBasePtr
) {
254 #if defined(__clang__)
255 # pragma clang diagnostic push
256 # pragma clang diagnostic ignored "-Wpointer-bool-conversion"
257 #elif defined(__GNUC__)
258 # pragma GCC diagnostic push
259 # pragma GCC diagnostic ignored "-Wnonnull-compare"
261 MOZ_ASSERT(aBasePtr
);
262 #if defined(__clang__)
263 # pragma clang diagnostic pop
264 #elif defined(__GNUC__)
265 # pragma GCC diagnostic pop
267 return NotNull
<T
*>{aBasePtr
};
270 // A variant of NotNull that can be used as a return value or parameter type and
271 // moved into both NotNull and non-NotNull targets. This is not possible with
272 // NotNull, as it is not movable. MovingNotNull can therefore not guarantee it
273 // is always non-nullptr, but it can't be dereferenced, and there are debug
274 // assertions that ensure it is only moved once.
275 template <typename T
>
276 class MOZ_NON_AUTOABLE MovingNotNull
{
277 template <typename U
>
278 friend constexpr MovingNotNull
<U
> WrapMovingNotNullUnchecked(U aBasePtr
);
282 bool mConsumed
= false;
285 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
286 template <typename U
>
287 constexpr explicit MovingNotNull(U aBasePtr
) : mBasePtr
{std::move(aBasePtr
)} {
289 static_assert(sizeof(T
) == sizeof(MovingNotNull
<T
>),
290 "NotNull must have zero space overhead.");
292 static_assert(offsetof(MovingNotNull
<T
>, mBasePtr
) == 0,
293 "mBasePtr must have zero offset.");
297 MovingNotNull() = delete;
299 MOZ_IMPLICIT
MovingNotNull(const NotNull
<T
>& aSrc
) : mBasePtr(aSrc
.get()) {}
301 template <typename U
>
302 MOZ_IMPLICIT
MovingNotNull(const NotNull
<U
>& aSrc
) : mBasePtr(aSrc
.get()) {}
304 template <typename U
>
305 MOZ_IMPLICIT
MovingNotNull(MovingNotNull
<U
>&& aSrc
)
306 : mBasePtr(std::move(aSrc
).unwrapBasePtr()) {}
308 MOZ_IMPLICIT
operator T() && { return std::move(*this).unwrapBasePtr(); }
310 MOZ_IMPLICIT
operator NotNull
<T
>() && { return std::move(*this).unwrap(); }
312 NotNull
<T
> unwrap() && {
313 return WrapNotNullUnchecked(std::move(*this).unwrapBasePtr());
316 T
unwrapBasePtr() && {
318 MOZ_ASSERT(!mConsumed
);
321 return std::move(mBasePtr
);
324 MovingNotNull(MovingNotNull
&&) = default;
325 MovingNotNull
& operator=(MovingNotNull
&&) = default;
328 template <typename T
>
329 constexpr MovingNotNull
<T
> WrapMovingNotNullUnchecked(T aBasePtr
) {
330 return MovingNotNull
<T
>{std::move(aBasePtr
)};
333 template <typename T
>
334 constexpr MovingNotNull
<T
> WrapMovingNotNull(T aBasePtr
) {
335 MOZ_RELEASE_ASSERT(aBasePtr
);
336 return WrapMovingNotNullUnchecked(std::move(aBasePtr
));
341 // Extract the pointed-to type from a pointer type (be it raw or smart).
342 // The default implementation uses the dereferencing operator of the pointer
343 // type to find what it's pointing to.
344 template <typename Pointer
>
346 // Remove the reference that dereferencing operators may return.
347 using Type
= std::remove_reference_t
<decltype(*std::declval
<Pointer
>())>;
348 using NonConstType
= std::remove_const_t
<Type
>;
351 // Specializations for raw pointers.
352 // This is especially required because VS 2017 15.6 (March 2018) started
353 // rejecting the above `decltype(*std::declval<Pointer>())` trick for raw
356 template <typename T
>
357 struct PointedTo
<T
*> {
359 using NonConstType
= T
;
362 template <typename T
>
363 struct PointedTo
<const T
*> {
364 using Type
= const T
;
365 using NonConstType
= T
;
368 } // namespace detail
370 // Allocate an object with infallible new, and wrap its pointer in NotNull.
371 // |MakeNotNull<Ptr<Ob>>(args...)| will run |new Ob(args...)|
372 // and return NotNull<Ptr<Ob>>.
373 template <typename T
, typename
... Args
>
374 constexpr NotNull
<T
> MakeNotNull(Args
&&... aArgs
) {
375 using Pointee
= typename
detail::PointedTo
<T
>::NonConstType
;
376 static_assert(!std::is_array_v
<Pointee
>,
377 "MakeNotNull cannot construct an array");
378 return NotNull
<T
>(new Pointee(std::forward
<Args
>(aArgs
)...));
381 // Compare two NotNulls.
382 template <typename T
, typename U
>
383 constexpr bool operator==(const NotNull
<T
>& aLhs
, const NotNull
<U
>& aRhs
) {
384 return aLhs
.get() == aRhs
.get();
386 template <typename T
, typename U
>
387 constexpr bool operator!=(const NotNull
<T
>& aLhs
, const NotNull
<U
>& aRhs
) {
388 return aLhs
.get() != aRhs
.get();
391 // Compare a NotNull to a base pointer.
392 template <typename T
, typename U
>
393 constexpr bool operator==(const NotNull
<T
>& aLhs
, const U
& aRhs
) {
394 return aLhs
.get() == aRhs
;
396 template <typename T
, typename U
>
397 constexpr bool operator!=(const NotNull
<T
>& aLhs
, const U
& aRhs
) {
398 return aLhs
.get() != aRhs
;
401 // Compare a base pointer to a NotNull.
402 template <typename T
, typename U
>
403 constexpr bool operator==(const T
& aLhs
, const NotNull
<U
>& aRhs
) {
404 return aLhs
== aRhs
.get();
406 template <typename T
, typename U
>
407 constexpr bool operator!=(const T
& aLhs
, const NotNull
<U
>& aRhs
) {
408 return aLhs
!= aRhs
.get();
411 // Disallow comparing a NotNull to a nullptr.
412 template <typename T
>
413 bool operator==(const NotNull
<T
>&, decltype(nullptr)) = delete;
414 template <typename T
>
415 bool operator!=(const NotNull
<T
>&, decltype(nullptr)) = delete;
417 // Disallow comparing a nullptr to a NotNull.
418 template <typename T
>
419 bool operator==(decltype(nullptr), const NotNull
<T
>&) = delete;
420 template <typename T
>
421 bool operator!=(decltype(nullptr), const NotNull
<T
>&) = delete;
423 } // namespace mozilla
425 #endif /* mozilla_NotNull_h */