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.
5 #ifndef BASE_FUNCTIONAL_DISALLOW_UNRETAINED_H_
6 #define BASE_FUNCTIONAL_DISALLOW_UNRETAINED_H_
8 // IMPORTANT: this is currently experimental. Use with caution, as the
9 // interaction with various base APIs is still unstable and subject to change.
11 // Types can opt to forbid use of `Unretained()`, et cetera by using this macro
12 // to annotate their class definition:
15 // DISALLOW_UNRETAINED();
20 // void PostAsyncWork() {
21 // // Will not compile.
22 // task_runner_->PostTask(
24 // base::BindOnce(&Dangerous::OnAsyncWorkDone, base::Unretained(this)));
27 // void OnAsyncWorkDone() {
32 // A type that disallows use of base::Unretained() can still be used with
35 // - If a type is only used on one sequence (e.g. `content::RenderFrameHostImpl`
36 // may only be used on the UI thread), embed a `base::WeakPtrFactory<T>` and
39 // - `GetSafeRef()` to bind a `SafeRef<T>` if `this` must *always* still be
40 // alive when the callback is invoked, e.g. binding Mojo reply callbacks
41 // when making Mojo calls through a `mojo::Remote` owned by `this`.
43 // - `GetWeakPtr()` to bind a `WeakPtr<T>` if the lifetimes are unclear, e.g.
44 // a task posted to main UI task runner, and a strong lifetime assertion is
47 // - Note 1: use `WeakPtr<T>` only when appropriate. `WeakPtr<T>` makes it
48 // harder to reason about lifetimes; while it is necessary and appropriate
49 // in many places, using it unnecessarily makes it hard to understand when
50 // one object is guaranteed to outlive another.
52 // - Note 2: whether `GetSafeRef()` or `GetWeakPtr()` is used, include
53 // comments to explain the assumptions behind the selection. Though these
54 // comments may become inaccurate over time, they are still valuable
55 // to helping when reading unfamiliar code.
57 // - If a type is used on multiple sequences, make it refcounted and either bind
58 // a `scoped_refptr<t>` or use `base::RetainedRef()`.
60 // - Consider if callbacks are needed at all; using abstractions like
61 // `base::SequenceBound<T>` make it much easier to manage cross-sequence
62 // lifetimes and avoid the need to write `base::Unretained()` at all.
63 #define DISALLOW_UNRETAINED() \
65 using DisallowBaseUnretainedMarker = void; \
68 /* No-op statement so use of this macro can be followed by `;`. */ \
71 #endif // BASE_FUNCTIONAL_DISALLOW_UNRETAINED_H_