blob: fe881b29e46753459268c6dcabd0640d024a798c [file] [log] [blame]
Jeroen Dhollandercda36982022-11-30 10:12:321// Copyright 2022 The Chromium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/check.h"
6#include "base/compiler_specific.h"
7
8#if CHECK_WILL_STREAM()
9#include "base/logging.h"
10#endif // CHECK_WILL_STREAM()
11
12#ifndef BASE_CHECK_DEREF_H_
13#define BASE_CHECK_DEREF_H_
14
15namespace logging {
16
17// Returns a reference to pointee of `ptr` if `ptr` is not null, or dies if
18// `ptr` is null.
19//
20// It is useful in initializers and direct assignments, where a direct `CHECK`
21// call can't be used:
22//
23// MyType& type_ref = CHECK_DEREF(MethodReturningAPointer());
24//
25// If your raw pointer is stored in a wrapped type like `unique_ptr` or
26// `raw_ptr`, you should use their `.get()` methods to get the raw pointer
27// before calling `CHECK_DEREF()`:
28//
29// MyType& type_ref = CHECK_DEREF(your_wrapped_pointer.get());
30//
Peter Boström2988b802025-01-03 11:51:3131#define CHECK_DEREF(ptr) ::logging::CheckDeref(ptr, #ptr " != nullptr")
Jeroen Dhollandercda36982022-11-30 10:12:3232
33template <typename T>
Peter Boström2988b802025-01-03 11:51:3134[[nodiscard]] T& CheckDeref(
35 T* ptr,
36 const char* message,
37 const base::Location& location = base::Location::Current()) {
Jeroen Dhollandercda36982022-11-30 10:12:3238 // Note: we can't just call `CHECK_NE(ptr, nullptr)` here, as that would
39 // cause the error to be reported from this header, and we want the error
40 // to be reported at the file and line of the caller.
Peter Kastingfa488992024-08-06 07:48:1441 if (ptr == nullptr) [[unlikely]] {
Peter Boström2988b802025-01-03 11:51:3142#if CHECK_WILL_STREAM()
43 // `CheckNoreturnError` will die with a fatal error in its destructor.
44 CheckNoreturnError::Check(message, location);
thefrog84e6049a2024-12-18 17:55:0845#else
Peter Boström2988b802025-01-03 11:51:3146 CheckFailure();
Jeroen Dhollandercda36982022-11-30 10:12:3247#endif // !CHECK_WILL_STREAM()
48 }
49 return *ptr;
50}
51
52} // namespace logging
53
54#endif // BASE_CHECK_DEREF_H_