Jeroen Dhollander | cda3698 | 2022-11-30 10:12:32 | [diff] [blame] | 1 | // 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 | |
| 15 | namespace 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öm | 2988b80 | 2025-01-03 11:51:31 | [diff] [blame] | 31 | #define CHECK_DEREF(ptr) ::logging::CheckDeref(ptr, #ptr " != nullptr") |
Jeroen Dhollander | cda3698 | 2022-11-30 10:12:32 | [diff] [blame] | 32 | |
| 33 | template <typename T> |
Peter Boström | 2988b80 | 2025-01-03 11:51:31 | [diff] [blame] | 34 | [[nodiscard]] T& CheckDeref( |
| 35 | T* ptr, |
| 36 | const char* message, |
| 37 | const base::Location& location = base::Location::Current()) { |
Jeroen Dhollander | cda3698 | 2022-11-30 10:12:32 | [diff] [blame] | 38 | // 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 Kasting | fa48899 | 2024-08-06 07:48:14 | [diff] [blame] | 41 | if (ptr == nullptr) [[unlikely]] { |
Peter Boström | 2988b80 | 2025-01-03 11:51:31 | [diff] [blame] | 42 | #if CHECK_WILL_STREAM() |
| 43 | // `CheckNoreturnError` will die with a fatal error in its destructor. |
| 44 | CheckNoreturnError::Check(message, location); |
thefrog | 84e6049a | 2024-12-18 17:55:08 | [diff] [blame] | 45 | #else |
Peter Boström | 2988b80 | 2025-01-03 11:51:31 | [diff] [blame] | 46 | CheckFailure(); |
Jeroen Dhollander | cda3698 | 2022-11-30 10:12:32 | [diff] [blame] | 47 | #endif // !CHECK_WILL_STREAM() |
| 48 | } |
| 49 | return *ptr; |
| 50 | } |
| 51 | |
| 52 | } // namespace logging |
| 53 | |
| 54 | #endif // BASE_CHECK_DEREF_H_ |