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 typename
= std::enable_if_t
<std::is_convertible_v
<const U
&, T
>>>
152 constexpr MOZ_IMPLICIT
NotNull(const NotNull
<U
>& aOther
)
153 : mBasePtr(aOther
.mBasePtr
) {}
155 template <typename U
,
156 typename
= std::enable_if_t
<std::is_convertible_v
<U
&&, T
>>>
157 constexpr MOZ_IMPLICIT
NotNull(MovingNotNull
<U
>&& aOther
)
158 : mBasePtr(std::move(aOther
).unwrapBasePtr()) {}
160 // Disallow null checks, which are unnecessary for this type.
161 explicit operator bool() const = delete;
163 // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
164 // get a castable pointer.
165 constexpr const T
& get() const { return mBasePtr
.mPtr
; }
167 // Implicit conversion to a base pointer. Preferable to get().
168 constexpr operator const T
&() const { return get(); }
170 // Implicit conversion to a raw pointer from const lvalue-reference if
171 // supported by the base pointer (for RefPtr<T> -> T* compatibility).
172 template <typename U
,
173 std::enable_if_t
<!std::is_pointer_v
<T
> &&
174 std::is_convertible_v
<const T
&, U
*>,
176 constexpr operator U
*() const& {
180 // Don't allow implicit conversions to raw pointers from rvalue-references.
181 template <typename U
,
182 std::enable_if_t
<!std::is_pointer_v
<T
> &&
183 std::is_convertible_v
<const T
&, U
*> &&
184 !std::is_convertible_v
<const T
&&, U
*>,
186 constexpr operator U
*() const&& = delete;
188 // Dereference operators.
189 constexpr auto* operator->() const MOZ_NONNULL_RETURN
{
190 return mBasePtr
.mPtr
.operator->();
192 constexpr decltype(*mBasePtr
.mPtr
) operator*() const {
193 return *mBasePtr
.mPtr
;
196 // NotNull can be copied, but not moved. Moving a NotNull with a smart base
197 // pointer would leave a nullptr NotNull behind. The move operations must not
198 // be explicitly deleted though, since that would cause overload resolution to
199 // fail in situations where a copy is possible.
200 NotNull(const NotNull
&) = default;
201 NotNull
& operator=(const NotNull
&) = default;
204 // Specialization for T* to allow adding MOZ_NONNULL_RETURN attributes.
205 template <typename T
>
207 template <typename U
>
208 friend constexpr NotNull
<U
> WrapNotNull(U aBasePtr
);
209 template <typename U
>
210 friend constexpr NotNull
<U
*> WrapNotNullUnchecked(U
* aBasePtr
);
211 template <typename U
, typename
... Args
>
212 friend constexpr NotNull
<U
> MakeNotNull(Args
&&... aArgs
);
213 template <typename U
>
214 friend class NotNull
;
218 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
219 template <typename U
>
220 constexpr explicit NotNull(U
* aBasePtr
) : mBasePtr(aBasePtr
) {}
223 // Disallow default construction.
226 // Construct/assign from another NotNull with a compatible base pointer type.
227 template <typename U
,
228 typename
= std::enable_if_t
<std::is_convertible_v
<const U
&, T
*>>>
229 constexpr MOZ_IMPLICIT
NotNull(const NotNull
<U
>& aOther
)
230 : mBasePtr(aOther
.get()) {
231 static_assert(sizeof(T
*) == sizeof(NotNull
<T
*>),
232 "NotNull must have zero space overhead.");
233 static_assert(offsetof(NotNull
<T
*>, mBasePtr
) == 0,
234 "mBasePtr must have zero offset.");
237 template <typename U
,
238 typename
= std::enable_if_t
<std::is_convertible_v
<U
&&, T
*>>>
239 constexpr MOZ_IMPLICIT
NotNull(MovingNotNull
<U
>&& aOther
)
240 : mBasePtr(NotNull
{std::move(aOther
)}) {}
242 // Disallow null checks, which are unnecessary for this type.
243 explicit operator bool() const = delete;
245 // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
246 // get a castable pointer.
247 constexpr T
* get() const MOZ_NONNULL_RETURN
{ return mBasePtr
; }
249 // Implicit conversion to a base pointer. Preferable to get().
250 constexpr operator T
*() const MOZ_NONNULL_RETURN
{ return get(); }
252 // Dereference operators.
253 constexpr T
* operator->() const MOZ_NONNULL_RETURN
{ return get(); }
254 constexpr T
& operator*() const { return *mBasePtr
; }
257 template <typename T
>
258 constexpr NotNull
<T
> WrapNotNull(T aBasePtr
) {
259 MOZ_RELEASE_ASSERT(aBasePtr
);
260 return NotNull
<T
>{std::move(aBasePtr
)};
263 // WrapNotNullUnchecked should only be used in situations, where it is
264 // statically known that aBasePtr is non-null, and redundant release assertions
265 // should be avoided. It is only defined for raw base pointers, since it is only
266 // needed for those right now. There is no fundamental reason not to allow
267 // arbitrary base pointers here.
268 template <typename T
>
269 constexpr NotNull
<T
> WrapNotNullUnchecked(T aBasePtr
) {
270 return NotNull
<T
>{std::move(aBasePtr
)};
273 template <typename T
>
275 constexpr NotNull
<T
*> WrapNotNullUnchecked(T
* const aBasePtr
) {
276 #if defined(__clang__)
277 # pragma clang diagnostic push
278 # pragma clang diagnostic ignored "-Wpointer-bool-conversion"
279 #elif defined(__GNUC__)
280 # pragma GCC diagnostic push
281 # pragma GCC diagnostic ignored "-Wnonnull-compare"
283 MOZ_ASSERT(aBasePtr
);
284 #if defined(__clang__)
285 # pragma clang diagnostic pop
286 #elif defined(__GNUC__)
287 # pragma GCC diagnostic pop
289 return NotNull
<T
*>{aBasePtr
};
292 // A variant of NotNull that can be used as a return value or parameter type and
293 // moved into both NotNull and non-NotNull targets. This is not possible with
294 // NotNull, as it is not movable. MovingNotNull can therefore not guarantee it
295 // is always non-nullptr, but it can't be dereferenced, and there are debug
296 // assertions that ensure it is only moved once.
297 template <typename T
>
298 class MOZ_NON_AUTOABLE MovingNotNull
{
299 template <typename U
>
300 friend constexpr MovingNotNull
<U
> WrapMovingNotNullUnchecked(U aBasePtr
);
304 bool mConsumed
= false;
307 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
308 template <typename U
>
309 constexpr explicit MovingNotNull(U aBasePtr
) : mBasePtr
{std::move(aBasePtr
)} {
311 static_assert(sizeof(T
) == sizeof(MovingNotNull
<T
>),
312 "NotNull must have zero space overhead.");
314 static_assert(offsetof(MovingNotNull
<T
>, mBasePtr
) == 0,
315 "mBasePtr must have zero offset.");
319 MovingNotNull() = delete;
321 MOZ_IMPLICIT
MovingNotNull(const NotNull
<T
>& aSrc
) : mBasePtr(aSrc
.get()) {}
323 template <typename U
,
324 typename
= std::enable_if_t
<std::is_convertible_v
<U
, T
>>>
325 MOZ_IMPLICIT
MovingNotNull(const NotNull
<U
>& aSrc
) : mBasePtr(aSrc
.get()) {}
327 template <typename U
,
328 typename
= std::enable_if_t
<std::is_convertible_v
<U
, T
>>>
329 MOZ_IMPLICIT
MovingNotNull(MovingNotNull
<U
>&& aSrc
)
330 : mBasePtr(std::move(aSrc
).unwrapBasePtr()) {}
332 MOZ_IMPLICIT
operator T() && { return std::move(*this).unwrapBasePtr(); }
334 MOZ_IMPLICIT
operator NotNull
<T
>() && { return std::move(*this).unwrap(); }
336 NotNull
<T
> unwrap() && {
337 return WrapNotNullUnchecked(std::move(*this).unwrapBasePtr());
340 T
unwrapBasePtr() && {
342 MOZ_ASSERT(!mConsumed
);
345 return std::move(mBasePtr
);
348 MovingNotNull(MovingNotNull
&&) = default;
349 MovingNotNull
& operator=(MovingNotNull
&&) = default;
352 template <typename T
>
353 constexpr MovingNotNull
<T
> WrapMovingNotNullUnchecked(T aBasePtr
) {
354 return MovingNotNull
<T
>{std::move(aBasePtr
)};
357 template <typename T
>
358 constexpr MovingNotNull
<T
> WrapMovingNotNull(T aBasePtr
) {
359 MOZ_RELEASE_ASSERT(aBasePtr
);
360 return WrapMovingNotNullUnchecked(std::move(aBasePtr
));
365 // Extract the pointed-to type from a pointer type (be it raw or smart).
366 // The default implementation uses the dereferencing operator of the pointer
367 // type to find what it's pointing to.
368 template <typename Pointer
>
370 // Remove the reference that dereferencing operators may return.
371 using Type
= std::remove_reference_t
<decltype(*std::declval
<Pointer
>())>;
372 using NonConstType
= std::remove_const_t
<Type
>;
375 // Specializations for raw pointers.
376 // This is especially required because VS 2017 15.6 (March 2018) started
377 // rejecting the above `decltype(*std::declval<Pointer>())` trick for raw
380 template <typename T
>
381 struct PointedTo
<T
*> {
383 using NonConstType
= T
;
386 template <typename T
>
387 struct PointedTo
<const T
*> {
388 using Type
= const T
;
389 using NonConstType
= T
;
392 } // namespace detail
394 // Allocate an object with infallible new, and wrap its pointer in NotNull.
395 // |MakeNotNull<Ptr<Ob>>(args...)| will run |new Ob(args...)|
396 // and return NotNull<Ptr<Ob>>.
397 template <typename T
, typename
... Args
>
398 constexpr NotNull
<T
> MakeNotNull(Args
&&... aArgs
) {
399 using Pointee
= typename
detail::PointedTo
<T
>::NonConstType
;
400 static_assert(!std::is_array_v
<Pointee
>,
401 "MakeNotNull cannot construct an array");
402 return NotNull
<T
>(new Pointee(std::forward
<Args
>(aArgs
)...));
405 // Compare two NotNulls.
406 template <typename T
, typename U
>
407 constexpr bool operator==(const NotNull
<T
>& aLhs
, const NotNull
<U
>& aRhs
) {
408 return aLhs
.get() == aRhs
.get();
410 template <typename T
, typename U
>
411 constexpr bool operator!=(const NotNull
<T
>& aLhs
, const NotNull
<U
>& aRhs
) {
412 return aLhs
.get() != aRhs
.get();
415 // Compare a NotNull to a base pointer.
416 template <typename T
, typename U
>
417 constexpr bool operator==(const NotNull
<T
>& aLhs
, const U
& aRhs
) {
418 return aLhs
.get() == aRhs
;
420 template <typename T
, typename U
>
421 constexpr bool operator!=(const NotNull
<T
>& aLhs
, const U
& aRhs
) {
422 return aLhs
.get() != aRhs
;
425 // Compare a base pointer to a NotNull.
426 template <typename T
, typename U
>
427 constexpr bool operator==(const T
& aLhs
, const NotNull
<U
>& aRhs
) {
428 return aLhs
== aRhs
.get();
430 template <typename T
, typename U
>
431 constexpr bool operator!=(const T
& aLhs
, const NotNull
<U
>& aRhs
) {
432 return aLhs
!= aRhs
.get();
435 // Disallow comparing a NotNull to a nullptr.
436 template <typename T
>
437 bool operator==(const NotNull
<T
>&, decltype(nullptr)) = delete;
438 template <typename T
>
439 bool operator!=(const NotNull
<T
>&, decltype(nullptr)) = delete;
441 // Disallow comparing a nullptr to a NotNull.
442 template <typename T
>
443 bool operator==(decltype(nullptr), const NotNull
<T
>&) = delete;
444 template <typename T
>
445 bool operator!=(decltype(nullptr), const NotNull
<T
>&) = delete;
447 } // namespace mozilla
449 #endif /* mozilla_NotNull_h */