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