observer_list_types.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2018 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_OBSERVER_LIST_TYPES_H_
  5. #define BASE_OBSERVER_LIST_TYPES_H_
  6. #include "base/base_export.h"
  7. #include "base/memory/weak_ptr.h"
  8. namespace base {
  9. namespace internal {
  10. class CheckedObserverAdapter;
  11. }
  12. // A CheckedObserver serves as a base class for an observer interface designed
  13. // to be used with base::ObserverList. It helps detect potential use-after-free
  14. // issues that can occur when observers fail to remove themselves from an
  15. // observer list upon destruction.
  16. //
  17. // A CheckedObserver will CHECK() if an ObserverList iteration is attempted over
  18. // a destroyed Observer.
  19. //
  20. // Note that a CheckedObserver subclass must be deleted on the same thread as
  21. // the ObserverList(s) it is added to. This is DCHECK()ed via WeakPtr.
  22. class BASE_EXPORT CheckedObserver {
  23. public:
  24. CheckedObserver();
  25. CheckedObserver(const CheckedObserver&) = delete;
  26. CheckedObserver& operator=(const CheckedObserver&) = delete;
  27. virtual ~CheckedObserver();
  28. // Returns whether |this| is in any ObserverList. Subclasses can CHECK() this
  29. // in their destructor to obtain a nicer stacktrace.
  30. bool IsInObserverList() const;
  31. private:
  32. friend class internal::CheckedObserverAdapter;
  33. // Must be mutable to allow ObserverList<const Foo>.
  34. mutable WeakPtrFactory<CheckedObserver> factory_{this};
  35. };
  36. } // namespace base
  37. #endif // BASE_OBSERVER_LIST_TYPES_H_