raw_scoped_refptr_mismatch_checker.h 2.1 KB

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