raw_scoped_refptr_mismatch_checker.h (2098B)
1 // Copyright 2011 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 #ifndef BASE_MEMORY_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_ 6 #define BASE_MEMORY_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_ 7 8 #include <type_traits> 9 10 #include "base/memory/raw_ptr.h" 11 #include "base/memory/raw_ref.h" 12 #include "base/template_util.h" 13 14 // It is dangerous to post a task with a T* argument where T is a subtype of 15 // RefCounted(Base|ThreadSafeBase), since by the time the parameter is used, the 16 // object may already have been deleted since it was not held with a 17 // scoped_refptr. Example: http://crbug.com/27191 18 // The following set of traits are designed to generate a compile error 19 // whenever this antipattern is attempted. 20 21 namespace base { 22 23 // This is a base internal implementation file used by task.h and callback.h. 24 // Not for public consumption, so we wrap it in namespace internal. 25 namespace internal { 26 27 template <typename T, typename = void> 28 struct IsRefCountedType : std::false_type {}; 29 30 template <typename T> 31 struct IsRefCountedType<T, 32 std::void_t<decltype(std::declval<T*>()->AddRef()), 33 decltype(std::declval<T*>()->Release())>> 34 : std::true_type {}; 35 36 // Human readable translation: you needed to be a scoped_refptr if you are a raw 37 // pointer type and are convertible to a RefCounted(Base|ThreadSafeBase) type. 38 template <typename T> 39 struct NeedsScopedRefptrButGetsRawPtr 40 : std::disjunction< 41 // TODO(danakj): Should ban native references and 42 // std::reference_wrapper here too. 43 std::conjunction<base::IsRawRef<T>, 44 IsRefCountedType<base::RemoveRawRefT<T>>>, 45 std::conjunction<base::IsPointer<T>, 46 IsRefCountedType<base::RemovePointerT<T>>>> { 47 static_assert(!std::is_reference_v<T>, 48 "NeedsScopedRefptrButGetsRawPtr requires non-reference type."); 49 }; 50 51 } // namespace internal 52 53 } // namespace base 54 55 #endif // BASE_MEMORY_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_