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. 4 5 #ifndef BASE_FUNCTIONAL_DISALLOW_UNRETAINED_H_ 6 #define BASE_FUNCTIONAL_DISALLOW_UNRETAINED_H_ 7 8 // IMPORTANT: this is currently experimental. Use with caution, as the 9 // interaction with various base APIs is still unstable and subject to change. 10 // 11 // Types can opt to forbid use of `Unretained()`, et cetera by using this macro 12 // to annotate their class definition: 13 // 14 // class Dangerous { 15 // DISALLOW_UNRETAINED(); 16 // public: 17 // 18 // ... 19 // 20 // void PostAsyncWork() { 21 // // Will not compile. 22 // task_runner_->PostTask( 23 // FROM_HERE, 24 // base::BindOnce(&Dangerous::OnAsyncWorkDone, base::Unretained(this))); 25 // } 26 // 27 // void OnAsyncWorkDone() { 28 // ... 29 // } 30 // }; 31 // 32 // A type that disallows use of base::Unretained() can still be used with 33 // callback: 34 // 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 37 // either use: 38 // 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`. 42 // 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 45 // not possible. 46 // 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. 51 // 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. 56 // 57 // - If a type is used on multiple sequences, make it refcounted and either bind 58 // a `scoped_refptr<t>` or use `base::RetainedRef()`. 59 // 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() \ 64 public: \ 65 using DisallowBaseUnretainedMarker [[maybe_unused]] = void; \ 66 \ 67 private: \ 68 /* No-op statement so use of this macro can be followed by `;`. */ \ 69 static_assert(true) 70 71 #endif // BASE_FUNCTIONAL_DISALLOW_UNRETAINED_H_ 72