tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 1 | # Callback<> and Bind() |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 2 | |
Raphael Kubo da Costa | 17c1618c | 2019-03-28 19:30:44 | [diff] [blame] | 3 | [TOC] |
| 4 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 5 | ## Introduction |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 6 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 7 | The templated `base::Callback<>` class is a generalized function object. |
| 8 | Together with the `base::Bind()` function in base/bind.h, they provide a |
| 9 | type-safe method for performing partial application of functions. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 10 | |
Matt Giuca | 7e81b22e | 2019-12-12 02:41:21 | [diff] [blame] | 11 | Partial application is the process of binding a subset of a function's arguments |
| 12 | to produce another function that takes fewer arguments. This can be used to pass |
| 13 | around a unit of delayed execution, much like lexical closures are used in other |
| 14 | languages. For example, it is used in Chromium code to schedule tasks on |
| 15 | different MessageLoops. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 16 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 17 | A callback with no unbound input parameters (`base::Callback<void()>`) is |
| 18 | called a `base::Closure`. Note that this is NOT the same as what other |
| 19 | languages refer to as a closure -- it does not retain a reference to its |
| 20 | enclosing environment. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 21 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 22 | ### OnceCallback<> And RepeatingCallback<> |
| 23 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 24 | `base::OnceCallback<>` and `base::RepeatingCallback<>` are next gen callback |
| 25 | classes, which are under development. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 26 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 27 | `base::OnceCallback<>` is created by `base::BindOnce()`. This is a callback |
| 28 | variant that is a move-only type and can be run only once. This moves out bound |
| 29 | parameters from its internal storage to the bound function by default, so it's |
| 30 | easier to use with movable types. This should be the preferred callback type: |
| 31 | since the lifetime of the callback is clear, it's simpler to reason about when |
| 32 | a callback that is passed between threads is destroyed. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 33 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 34 | `base::RepeatingCallback<>` is created by `base::BindRepeating()`. This is a |
| 35 | callback variant that is copyable that can be run multiple times. It uses |
| 36 | internal ref-counting to make copies cheap. However, since ownership is shared, |
| 37 | it is harder to reason about when the callback and the bound state are |
| 38 | destroyed, especially when the callback is passed between threads. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 39 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 40 | The legacy `base::Callback<>` is currently aliased to |
| 41 | `base::RepeatingCallback<>`. In new code, prefer `base::OnceCallback<>` where |
| 42 | possible, and use `base::RepeatingCallback<>` otherwise. Once the migration is |
| 43 | complete, the type alias will be removed and `base::OnceCallback<>` will be renamed |
| 44 | to `base::Callback<>` to emphasize that it should be preferred. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 45 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 46 | `base::RepeatingCallback<>` is convertible to `base::OnceCallback<>` by the |
| 47 | implicit conversion. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 48 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 49 | ### Memory Management And Passing |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 50 | |
danakj | e26d7cf | 2019-05-29 20:04:14 | [diff] [blame] | 51 | Pass `base::{Once,Repeating}Callback` objects by value if ownership is |
| 52 | transferred; otherwise, pass it by const-reference. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 53 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 54 | ```cpp |
| 55 | // |Foo| just refers to |cb| but doesn't store it nor consume it. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 56 | bool Foo(const base::OnceCallback<void(int)>& cb) { |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 57 | return cb.is_null(); |
| 58 | } |
| 59 | |
| 60 | // |Bar| takes the ownership of |cb| and stores |cb| into |g_cb|. |
danakj | e26d7cf | 2019-05-29 20:04:14 | [diff] [blame] | 61 | base::RepeatingCallback<void(int)> g_cb; |
| 62 | void Bar(base::RepeatingCallback<void(int)> cb) { |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 63 | g_cb = std::move(cb); |
| 64 | } |
| 65 | |
| 66 | // |Baz| takes the ownership of |cb| and consumes |cb| by Run(). |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 67 | void Baz(base::OnceCallback<void(int)> cb) { |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 68 | std::move(cb).Run(42); |
| 69 | } |
| 70 | |
| 71 | // |Qux| takes the ownership of |cb| and transfers ownership to PostTask(), |
| 72 | // which also takes the ownership of |cb|. |
danakj | e26d7cf | 2019-05-29 20:04:14 | [diff] [blame] | 73 | void Qux(base::RepeatingCallback<void(int)> cb) { |
| 74 | PostTask(FROM_HERE, base::BindOnce(cb, 42)); |
| 75 | PostTask(FROM_HERE, base::BindOnce(std::move(cb), 43)); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 76 | } |
| 77 | ``` |
| 78 | |
danakj | e26d7cf | 2019-05-29 20:04:14 | [diff] [blame] | 79 | When you pass a `base::{Once,Repeating}Callback` object to a function parameter, |
| 80 | use `std::move()` if you don't need to keep a reference to it, otherwise, pass the |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 81 | object directly. You may see a compile error when the function requires the |
| 82 | exclusive ownership, and you didn't pass the callback by move. Note that the |
danakj | e26d7cf | 2019-05-29 20:04:14 | [diff] [blame] | 83 | moved-from `base::{Once,Repeating}Callback` becomes null, as if its `Reset()` |
| 84 | method had been called. Afterward, its `is_null()` method will return true and |
| 85 | its `operator bool()` will return false. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 86 | |
danakj | fcc5e7c | 2020-10-23 17:43:27 | [diff] [blame] | 87 | ### Chaining callbacks |
| 88 | |
| 89 | When you have 2 callbacks that you wish to run in sequence, they can be joined |
| 90 | together into a single callback through the use of `Then()`. |
| 91 | |
| 92 | Calling `Then()` on a `base::OnceCallback` joins a second callback that will be |
| 93 | run together with, but after, the first callback. The return value from the |
| 94 | first callback is passed along to the second, and the return value from the |
| 95 | second callback is returned at the end. More concretely, calling `a.Then(b)` |
| 96 | produces a new `base::OnceCallback` that will run `b(a());`, returning the |
| 97 | result from `b`. |
| 98 | |
| 99 | This example uses `Then()` to join 2 `base::OnceCallback`s together: |
| 100 | ```cpp |
| 101 | int Floor(float f) { return std::floor(f); } |
| 102 | std::string IntToString(int i) { return base::NumberToString(i); } |
| 103 | |
| 104 | base::OnceCallback<int(float)> first = base::BindOnce(&Floor); |
| 105 | base::OnceCallback<std::string(int)> second = base::BindOnce(&IntToString); |
| 106 | |
| 107 | // This will run |first|, run and pass the result to |second|, then return |
| 108 | // the result from |second|. |
| 109 | std::string r = std::move(first).Then(std::move(second)).Run(3.5f); |
| 110 | // |r| will be "3". |first| and |second| are now both null, as they were |
| 111 | // consumed to perform the join operation. |
| 112 | ``` |
| 113 | |
| 114 | Similarly, `Then()` also works with `base::RepeatingCallback`; however, the |
| 115 | joined callback must also be a `base::RepeatingCallback` to ensure the resulting |
| 116 | callback can be invoked multiple times. |
| 117 | |
| 118 | This example uses `Then()` to join 2 `base::RepeatingCallback`s together: |
| 119 | ```cpp |
| 120 | int Floor(float f) { return std::floor(f); } |
| 121 | std::string IntToString(int i) { return base::NumberToString(i); } |
| 122 | |
| 123 | base::RepeatingCallback<int(float)> first = base::BindRepeating(&Floor); |
| 124 | base::RepeatingCallback<std::string(int)> second = base::BindRepeating(&IntToString); |
| 125 | |
| 126 | // This creates a RepeatingCallback that will run |first|, run and pass the |
| 127 | // result to |second|, then return the result from |second|. |
| 128 | base::RepeatingCallback<std::string(float)> joined = |
| 129 | std::move(first).Then(std::move(second)); |
| 130 | // |first| and |second| are now both null, as they were consumed to perform |
| 131 | // the join operation. |
| 132 | |
| 133 | // This runs the functor that was originally bound to |first|, then |second|. |
| 134 | std::string r = joined.Run(3.5); |
| 135 | // |r| will be "3". |
| 136 | |
| 137 | // It's valid to call it multiple times since all callbacks involved are |
| 138 | // base::RepeatingCallbacks. |
| 139 | r = joined.Run(2.5); |
| 140 | // |r| is set to "2". |
| 141 | ``` |
| 142 | |
| 143 | In the above example, casting the `base::RepeatingCallback` to an r-value with |
| 144 | `std::move()` causes `Then()` to destroy the original callback, in the same way |
| 145 | that occurs for joining `base::OnceCallback`s. However since a |
| 146 | `base::RepeatingCallback` can be run multiple times, it can be joined |
| 147 | non-destructively as well. |
| 148 | ```cpp |
| 149 | int Floor(float f) { return std::floor(f); } |
| 150 | std::string IntToString(int i) { return base::NumberToString(i); } |
| 151 | |
| 152 | base::RepeatingCallback<int(float)> first = base::BindRepeating(&Floor); |
| 153 | base::RepeatingCallback<std::string(int)> second = base::BindRepeating(&IntToString); |
| 154 | |
| 155 | // This creates a RepeatingCallback that will run |first|, run and pass the |
| 156 | // result to |second|, then return the result from |second|. |
| 157 | std::string r = first.Then(second).Run(3.5f); |
| 158 | // |r| will be 3, and |first| and |second| are still valid to use. |
| 159 | |
| 160 | // Runs Floor(). |
| 161 | int i = first.Run(5.5); |
| 162 | // Runs IntToString(). |
| 163 | std::string s = second.Run(9); |
| 164 | ``` |
| 165 | |
danakj | 9335cb1c | 2020-10-28 20:21:21 | [diff] [blame] | 166 | If the second callback does not want to receive a value from the first callback, |
| 167 | you may use `base::IgnoreResult` to drop the return value in between running the |
| 168 | two. |
| 169 | |
| 170 | ```cpp |
| 171 | // Returns an integer. |
| 172 | base::RepeatingCallback<int()> first = base::BindRepeating([](){ return 5; }); |
| 173 | // Does not want to receive an integer. |
| 174 | base::RepeatingClosure second = base::BindRepeating([](){}); |
| 175 | |
| 176 | // This will not compile, because |second| can not receive the return value from |
| 177 | // |first|. |
| 178 | // first.Then(second).Run(); |
| 179 | |
| 180 | // We can drop the result from |first| before running second. |
| 181 | base::BindRepeating(base::IgnoreResult(first)).Then(second).Run(); |
| 182 | // This will effectively create a callback that when Run() will call |
| 183 | // `first(); second();` instead of `second(first());`. |
| 184 | ``` |
| 185 | |
| 186 | Note that the return value from |first| will be lost in the above example, and |
| 187 | would be destroyed before |second| is run. If you want the return value from |
| 188 | |first| to be preserved and ultimately returned after running both |first| and |
| 189 | |second|, then you would need a primitive such as the `base::PassThrough<T>()` |
| 190 | helper in the [base::PassThrough CL](https://chromium-review.googlesource.com/c/chromium/src/+/2493243). |
| 191 | If this would be helpful for you, please let [email protected] know or ping |
| 192 | the CL. |
| 193 | |
kylechar | dde7d23 | 2020-11-16 17:35:09 | [diff] [blame] | 194 | ### Chaining callbacks across different task runners |
| 195 | |
| 196 | ```cpp |
| 197 | // The task runner for a different thread. |
| 198 | scoped_refptr<base::SequencedTaskRunner> other_task_runner = ...; |
| 199 | |
| 200 | // A function to compute some interesting result, except it can only be run |
| 201 | // safely from `other_task_runner` and not the current thread. |
| 202 | int ComputeResult(); |
| 203 | |
| 204 | base::OnceCallback<int()> compute_result_cb = base::BindOnce(&ComputeResult); |
| 205 | |
| 206 | // Task runner for the current thread. |
| 207 | scoped_refptr<base::SequencedTaskRunner> current_task_runner = |
| 208 | base::SequencedTaskRunnerHandle::Get(); |
| 209 | |
| 210 | // A function to accept the result, except it can only be run safely from the |
| 211 | // current thread. |
| 212 | void ProvideResult(int result); |
| 213 | |
| 214 | base::OnceCallback<void(int)> provide_result_cb = |
| 215 | base::BindOnce(&ProvideResult); |
| 216 | ``` |
| 217 | |
| 218 | Using `Then()` to join `compute_result_cb` and `provide_result_cb` directly |
| 219 | would be inappropriate. `ComputeResult()` and `ProvideResult()` would run on the |
| 220 | same thread which isn't safe. However, `base::BindPostTask()` can be used to |
| 221 | ensure `provide_result_cb` will run on `current_task_runner`. |
| 222 | |
| 223 | ```cpp |
| 224 | // The following two statements post a task to `other_task_runner` to run |
| 225 | // `task`. This will invoke ComputeResult() on a different thread to get the |
| 226 | // result value then post a task back to `current_task_runner` to invoke |
| 227 | // ProvideResult() with the result. |
| 228 | OnceClosure task = |
| 229 | std::move(compute_result_cb) |
| 230 | .Then(base::BindPostTask(current_task_runner, |
| 231 | std::move(provide_result_cb))); |
| 232 | other_task_runner->PostTask(FROM_HERE, std::move(task)); |
| 233 | ``` |
| 234 | |
Thomas Guilbert | 5db5238 | 2020-12-17 22:33:14 | [diff] [blame] | 235 | ### Splitting a OnceCallback in two |
| 236 | |
| 237 | If a callback is only run once, but two references need to be held to the |
| 238 | callback, using a `base::OnceCallback` can be clearer than a |
| 239 | `base::RepeatingCallback`, from an intent and semantics point of view. |
| 240 | `base::SplitOnceCallback()` takes a `base::OnceCallback` and returns a pair of |
| 241 | callbacks with the same signature. When either of the returned callback is run, |
| 242 | the original callback is invoked. Running the leftover callback will result in a |
| 243 | crash. |
| 244 | This can be useful when passing a `base::OnceCallback` to a function that may or |
| 245 | may not take ownership of the callback. E.g, when an object creation could fail: |
| 246 | |
| 247 | ```cpp |
| 248 | std::unique_ptr<FooTask> CreateFooTask(base::OnceClosure task) { |
| 249 | std::pair<base::OnceClosure,base::OnceClosure> split |
| 250 | = base::SplitOnceCallback(std::move(task)); |
| 251 | |
| 252 | std::unique_ptr<FooTask> foo = TryCreateFooTask(std::move(split.first)); |
| 253 | if (foo) |
| 254 | return foo; |
| 255 | |
| 256 | return CreateFallbackFooTask(std::move(split.second)); |
| 257 | } |
| 258 | ``` |
| 259 | |
| 260 | While it is best to use a single callback to report success/failure, some APIs |
| 261 | already take multiple callbacks. `base::SplitOnceCallback()` can be used to |
| 262 | split a completion callback and help in such a case: |
| 263 | |
| 264 | ```cpp |
| 265 | using StatusCallback = base::OnceCallback<void(FooStatus)>; |
| 266 | void DoOperation(StatusCallback done_cb) { |
| 267 | std::pair<StatusCallback, StatusCallback> split |
| 268 | = base::SplitOnceCallback(std::move(done_cb)); |
| 269 | |
| 270 | InnerWork(BindOnce(std::move(split.first), STATUS_OK), |
| 271 | BindOnce(std::move(split.second), STATUS_ABORTED)); |
| 272 | } |
| 273 | |
| 274 | void InnerWork(base::OnceClosure work_done_cb, |
| 275 | base::OnceClosure work_aborted_cb); |
| 276 | ``` |
| 277 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 278 | ## Quick reference for basic stuff |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 279 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 280 | ### Binding A Bare Function |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 281 | |
| 282 | ```cpp |
| 283 | int Return5() { return 5; } |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 284 | base::OnceCallback<int()> func_cb = base::BindOnce(&Return5); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 285 | LOG(INFO) << std::move(func_cb).Run(); // Prints 5. |
| 286 | ``` |
| 287 | |
| 288 | ```cpp |
| 289 | int Return5() { return 5; } |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 290 | base::RepeatingCallback<int()> func_cb = base::BindRepeating(&Return5); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 291 | LOG(INFO) << func_cb.Run(); // Prints 5. |
| 292 | ``` |
| 293 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 294 | ### Binding A Captureless Lambda |
| 295 | |
| 296 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 297 | base::Callback<int()> lambda_cb = base::Bind([] { return 4; }); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 298 | LOG(INFO) << lambda_cb.Run(); // Print 4. |
| 299 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 300 | base::OnceCallback<int()> lambda_cb2 = base::BindOnce([] { return 3; }); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 301 | LOG(INFO) << std::move(lambda_cb2).Run(); // Print 3. |
Erik Chen | 9425c0f | 2020-09-11 21:41:09 | [diff] [blame] | 302 | |
| 303 | base::OnceCallback<int()> lambda_cb3 = base::BindOnce([] { return 2; }); |
| 304 | base::OnceCallback<int(base::OnceCallback<int()>)> lambda_cb4 = |
| 305 | base::BindOnce( |
| 306 | [](base::OnceCallback<int()> callback) { |
| 307 | return std::move(callback).Run(); }, |
| 308 | std::move(lambda_cb3)); |
| 309 | LOG(INFO) << std::move(lambda_cb4).Run(); // Print 2. |
| 310 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 311 | ``` |
| 312 | |
Raphael Kubo da Costa | 17c1618c | 2019-03-28 19:30:44 | [diff] [blame] | 313 | ### Binding A Capturing Lambda (In Tests) |
| 314 | |
| 315 | When writing tests, it is often useful to capture arguments that need to be |
| 316 | modified in a callback. |
| 317 | |
| 318 | ``` cpp |
Guido Urdaneta | ef4e9194 | 2020-11-09 15:06:24 | [diff] [blame] | 319 | #include "base/test/bind.h" |
Raphael Kubo da Costa | 17c1618c | 2019-03-28 19:30:44 | [diff] [blame] | 320 | |
| 321 | int i = 2; |
| 322 | base::Callback<void()> lambda_cb = base::BindLambdaForTesting([&]() { i++; }); |
| 323 | lambda_cb.Run(); |
| 324 | LOG(INFO) << i; // Print 3; |
| 325 | ``` |
| 326 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 327 | ### Binding A Class Method |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 328 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 329 | The first argument to bind is the member function to call, the second is the |
| 330 | object on which to call it. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 331 | |
| 332 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 333 | class Ref : public base::RefCountedThreadSafe<Ref> { |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 334 | public: |
| 335 | int Foo() { return 3; } |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 336 | }; |
| 337 | scoped_refptr<Ref> ref = new Ref(); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 338 | base::Callback<void()> ref_cb = base::Bind(&Ref::Foo, ref); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 339 | LOG(INFO) << ref_cb.Run(); // Prints out 3. |
| 340 | ``` |
| 341 | |
| 342 | By default the object must support RefCounted or you will get a compiler |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 343 | error. If you're passing between threads, be sure it's RefCountedThreadSafe! See |
| 344 | "Advanced binding of member functions" below if you don't want to use reference |
| 345 | counting. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 346 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 347 | ### Running A Callback |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 348 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 349 | Callbacks can be run with their `Run` method, which has the same signature as |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 350 | the template argument to the callback. Note that `base::OnceCallback::Run` |
| 351 | consumes the callback object and can only be invoked on a callback rvalue. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 352 | |
| 353 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 354 | void DoSomething(const base::Callback<void(int, std::string)>& callback) { |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 355 | callback.Run(5, "hello"); |
| 356 | } |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 357 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 358 | void DoSomethingOther(base::OnceCallback<void(int, std::string)> callback) { |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 359 | std::move(callback).Run(5, "hello"); |
| 360 | } |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 361 | ``` |
| 362 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 363 | RepeatingCallbacks can be run more than once (they don't get deleted or marked |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 364 | when run). However, this precludes using `base::Passed` (see below). |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 365 | |
| 366 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 367 | void DoSomething(const base::RepeatingCallback<double(double)>& callback) { |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 368 | double myresult = callback.Run(3.14159); |
| 369 | myresult += callback.Run(2.71828); |
| 370 | } |
| 371 | ``` |
| 372 | |
michaelpg | 0f156e1 | 2017-03-18 02:49:09 | [diff] [blame] | 373 | If running a callback could result in its own destruction (e.g., if the callback |
| 374 | recipient deletes the object the callback is a member of), the callback should |
Greg Thompson | ddc84d4 | 2021-01-04 10:10:02 | [diff] [blame] | 375 | be moved or copied onto the stack before it can be safely invoked. (Note that |
| 376 | this is only an issue for RepeatingCallbacks, because a OnceCallback always has |
| 377 | to be moved for execution.) |
michaelpg | 0f156e1 | 2017-03-18 02:49:09 | [diff] [blame] | 378 | |
| 379 | ```cpp |
| 380 | void Foo::RunCallback() { |
Bence Béky | 1532745 | 2018-05-10 20:59:07 | [diff] [blame] | 381 | std::move(&foo_deleter_callback_).Run(); |
michaelpg | 0f156e1 | 2017-03-18 02:49:09 | [diff] [blame] | 382 | } |
| 383 | ``` |
| 384 | |
Peter Kasting | 341e1fb | 2018-02-24 00:03:01 | [diff] [blame] | 385 | ### Creating a Callback That Does Nothing |
| 386 | |
| 387 | Sometimes you need a callback that does nothing when run (e.g. test code that |
| 388 | doesn't care to be notified about certain types of events). It may be tempting |
| 389 | to pass a default-constructed callback of the right type: |
| 390 | |
| 391 | ```cpp |
| 392 | using MyCallback = base::OnceCallback<void(bool arg)>; |
| 393 | void MyFunction(MyCallback callback) { |
| 394 | std::move(callback).Run(true); // Uh oh... |
| 395 | } |
| 396 | ... |
| 397 | MyFunction(MyCallback()); // ...this will crash when Run()! |
| 398 | ``` |
| 399 | |
| 400 | Default-constructed callbacks are null, and thus cannot be Run(). Instead, use |
| 401 | `base::DoNothing()`: |
| 402 | |
| 403 | ```cpp |
| 404 | ... |
| 405 | MyFunction(base::DoNothing()); // Can be Run(), will no-op |
| 406 | ``` |
| 407 | |
| 408 | `base::DoNothing()` can be passed for any OnceCallback or RepeatingCallback that |
| 409 | returns void. |
| 410 | |
| 411 | Implementation-wise, `base::DoNothing()` is actually a functor which produces a |
| 412 | callback from `operator()`. This makes it unusable when trying to bind other |
| 413 | arguments to it. Normally, the only reason to bind arguments to DoNothing() is |
| 414 | to manage object lifetimes, and in these cases, you should strive to use idioms |
| 415 | like DeleteSoon(), ReleaseSoon(), or RefCountedDeleteOnSequence instead. If you |
| 416 | truly need to bind an argument to DoNothing(), or if you need to explicitly |
| 417 | create a callback object (because implicit conversion through operator()() won't |
| 418 | compile), you can instantiate directly: |
| 419 | |
| 420 | ```cpp |
| 421 | // Binds |foo_ptr| to a no-op OnceCallback takes a scoped_refptr<Foo>. |
| 422 | // ANTIPATTERN WARNING: This should likely be changed to ReleaseSoon()! |
| 423 | base::Bind(base::DoNothing::Once<scoped_refptr<Foo>>(), foo_ptr); |
| 424 | ``` |
| 425 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 426 | ### Passing Unbound Input Parameters |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 427 | |
| 428 | Unbound parameters are specified at the time a callback is `Run()`. They are |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 429 | specified in the `base::Callback` template type: |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 430 | |
| 431 | ```cpp |
| 432 | void MyFunc(int i, const std::string& str) {} |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 433 | base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 434 | cb.Run(23, "hello, world"); |
| 435 | ``` |
| 436 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 437 | ### Passing Bound Input Parameters |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 438 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 439 | Bound parameters are specified when you create the callback as arguments to |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 440 | `base::Bind()`. They will be passed to the function and the `Run()`ner of the |
| 441 | callback doesn't see those values or even know that the function it's calling. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 442 | |
| 443 | ```cpp |
| 444 | void MyFunc(int i, const std::string& str) {} |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 445 | base::Callback<void()> cb = base::Bind(&MyFunc, 23, "hello world"); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 446 | cb.Run(); |
| 447 | ``` |
| 448 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 449 | A callback with no unbound input parameters (`base::Callback<void()>`) is |
| 450 | called a `base::Closure`. So we could have also written: |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 451 | |
| 452 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 453 | base::Closure cb = base::Bind(&MyFunc, 23, "hello world"); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 454 | ``` |
| 455 | |
| 456 | When calling member functions, bound parameters just go after the object |
| 457 | pointer. |
| 458 | |
| 459 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 460 | base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world"); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 461 | ``` |
| 462 | |
Matt Giuca | 7e81b22e | 2019-12-12 02:41:21 | [diff] [blame] | 463 | ### Partial Binding Of Parameters |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 464 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 465 | You can specify some parameters when you create the callback, and specify the |
| 466 | rest when you execute the callback. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 467 | |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 468 | When calling a function bound parameters are first, followed by unbound |
| 469 | parameters. |
| 470 | |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 471 | ```cpp |
| 472 | void ReadIntFromFile(const std::string& filename, |
| 473 | base::OnceCallback<void(int)> on_read); |
| 474 | |
| 475 | void DisplayIntWithPrefix(const std::string& prefix, int result) { |
| 476 | LOG(INFO) << prefix << result; |
| 477 | } |
| 478 | |
| 479 | void AnotherFunc(const std::string& file) { |
| 480 | ReadIntFromFile(file, base::BindOnce(&DisplayIntWithPrefix, "MyPrefix: ")); |
| 481 | }; |
| 482 | ``` |
| 483 | |
Matt Giuca | 7e81b22e | 2019-12-12 02:41:21 | [diff] [blame] | 484 | This technique is known as [partial |
| 485 | application](http://en.wikipedia.org/wiki/Partial_application). It should be |
| 486 | used in lieu of creating an adapter class that holds the bound arguments. Notice |
| 487 | also that the `"MyPrefix: "` argument is actually a `const char*`, while |
| 488 | `DisplayIntWithPrefix` actually wants a `const std::string&`. Like normal |
| 489 | function dispatch, `base::Bind`, will coerce parameter types if possible. |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 490 | |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 491 | ### Avoiding Copies With Callback Parameters |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 492 | |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 493 | A parameter of `base::BindRepeating()` or `base::BindOnce()` is moved into its |
| 494 | internal storage if it is passed as a rvalue. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 495 | |
| 496 | ```cpp |
| 497 | std::vector<int> v = {1, 2, 3}; |
| 498 | // |v| is moved into the internal storage without copy. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 499 | base::Bind(&Foo, std::move(v)); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 500 | ``` |
| 501 | |
| 502 | ```cpp |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 503 | // The vector is moved into the internal storage without copy. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 504 | base::Bind(&Foo, std::vector<int>({1, 2, 3})); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 505 | ``` |
| 506 | |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 507 | Arguments bound with `base::BindOnce()` are always moved, if possible, to the |
| 508 | target function. |
| 509 | A function parameter that is passed by value and has a move constructor will be |
| 510 | moved instead of copied. |
| 511 | This makes it easy to use move-only types with `base::BindOnce()`. |
| 512 | |
| 513 | In contrast, arguments bound with `base::BindRepeating()` are only moved to the |
| 514 | target function if the argument is bound with `base::Passed()`. |
| 515 | |
| 516 | **DANGER**: |
| 517 | A `base::RepeatingCallback` can only be run once if arguments were bound with |
| 518 | `base::Passed()`. |
| 519 | For this reason, avoid `base::Passed()`. |
| 520 | If you know a callback will only be called once, prefer to refactor code to |
| 521 | work with `base::OnceCallback` instead. |
| 522 | |
| 523 | Avoid using `base::Passed()` with `base::BindOnce()`, as `std::move()` does the |
| 524 | same thing and is more familiar. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 525 | |
| 526 | ```cpp |
| 527 | void Foo(std::unique_ptr<int>) {} |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 528 | auto p = std::make_unique<int>(42); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 529 | |
| 530 | // |p| is moved into the internal storage of Bind(), and moved out to |Foo|. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 531 | base::BindOnce(&Foo, std::move(p)); |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 532 | base::BindRepeating(&Foo, base::Passed(&p)); // Ok, but subtle. |
| 533 | base::BindRepeating(&Foo, base::Passed(std::move(p))); // Ok, but subtle. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 534 | ``` |
| 535 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 536 | ## Quick reference for advanced binding |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 537 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 538 | ### Binding A Class Method With Weak Pointers |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 539 | |
Wez | 3327626 | 2019-06-21 00:11:20 | [diff] [blame] | 540 | If `MyClass` has a `base::WeakPtr<MyClass> weak_this_` member (see below) |
| 541 | then a class method can be bound with: |
| 542 | |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 543 | ```cpp |
Wez | 3327626 | 2019-06-21 00:11:20 | [diff] [blame] | 544 | base::Bind(&MyClass::Foo, weak_this_); |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 545 | ``` |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 546 | |
| 547 | The callback will not be run if the object has already been destroyed. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 548 | |
Wez | 3327626 | 2019-06-21 00:11:20 | [diff] [blame] | 549 | Note that class method callbacks bound to `base::WeakPtr`s may only be |
| 550 | run on the same sequence on which the object will be destroyed, since otherwise |
| 551 | execution of the callback might race with the object's deletion. |
| 552 | |
| 553 | To use `base::WeakPtr` with `base::Bind()`, `MyClass` will typically look like: |
| 554 | |
| 555 | ```cpp |
| 556 | class MyClass { |
| 557 | public: |
Jeremy Roman | 0dd0b2f | 2019-07-16 21:00:43 | [diff] [blame] | 558 | MyClass() { |
Wez | 3327626 | 2019-06-21 00:11:20 | [diff] [blame] | 559 | weak_this_ = weak_factory_.GetWeakPtr(); |
| 560 | } |
| 561 | private: |
| 562 | base::WeakPtr<MyClass> weak_this_; |
| 563 | // MyClass member variables go here. |
Jeremy Roman | 0dd0b2f | 2019-07-16 21:00:43 | [diff] [blame] | 564 | base::WeakPtrFactory<MyClass> weak_factory_{this}; |
Wez | 3327626 | 2019-06-21 00:11:20 | [diff] [blame] | 565 | }; |
| 566 | ``` |
| 567 | |
| 568 | `weak_factory_` is the last member variable in `MyClass` so that it is |
| 569 | destroyed first. This ensures that if any class methods bound to `weak_this_` |
| 570 | are `Run()` during teardown, then they will not actually be executed. |
| 571 | |
| 572 | If `MyClass` only ever `base::Bind()`s and executes callbacks on the same |
| 573 | sequence, then it is generally safe to call `weak_factory_.GetWeakPtr()` at the |
| 574 | `base::Bind()` call, rather than taking a separate `weak_this_` during |
| 575 | construction. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 576 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 577 | ### Binding A Class Method With Manual Lifetime Management |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 578 | |
| 579 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 580 | base::Bind(&MyClass::Foo, base::Unretained(this)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 581 | ``` |
| 582 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 583 | This disables all lifetime management on the object. You're responsible for |
| 584 | making sure the object is alive at the time of the call. You break it, you own |
| 585 | it! |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 586 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 587 | ### Binding A Class Method And Having The Callback Own The Class |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 588 | |
| 589 | ```cpp |
| 590 | MyClass* myclass = new MyClass; |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 591 | base::Bind(&MyClass::Foo, base::Owned(myclass)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 592 | ``` |
| 593 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 594 | The object will be deleted when the callback is destroyed, even if it's not run |
| 595 | (like if you post a task during shutdown). Potentially useful for "fire and |
| 596 | forget" cases. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 597 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 598 | Smart pointers (e.g. `std::unique_ptr<>`) are also supported as the receiver. |
| 599 | |
| 600 | ```cpp |
| 601 | std::unique_ptr<MyClass> myclass(new MyClass); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 602 | base::Bind(&MyClass::Foo, std::move(myclass)); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 603 | ``` |
| 604 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 605 | ### Ignoring Return Values |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 606 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 607 | Sometimes you want to call a function that returns a value in a callback that |
| 608 | doesn't expect a return value. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 609 | |
| 610 | ```cpp |
Wen Fan | dd47202 | 2021-03-12 01:31:09 | [diff] [blame^] | 611 | int DoSomething(int arg) { |
| 612 | cout << arg << endl; |
| 613 | return arg; |
| 614 | } |
danakj | 9335cb1c | 2020-10-28 20:21:21 | [diff] [blame] | 615 | base::RepeatingCallback<void(int)> cb = |
| 616 | base::BindRepeating(IgnoreResult(&DoSomething)); |
| 617 | ``` |
| 618 | |
| 619 | Similarly, you may want to use an existing callback that returns a value in a |
| 620 | place that expects a void return type. |
| 621 | |
| 622 | ```cpp |
| 623 | base::RepeatingCallback<int()> cb = base::BindRepeating([](){ return 5; }); |
| 624 | base::RepeatingClosure void_cb = base::BindRepeating(base::IgnoreResult(cb)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 625 | ``` |
| 626 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 627 | ## Quick reference for binding parameters to Bind() |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 628 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 629 | Bound parameters are specified as arguments to `base::Bind()` and are passed to |
| 630 | the function. A callback with no parameters or no unbound parameters is called |
| 631 | a `base::Closure` (`base::Callback<void()>` and `base::Closure` are the same |
| 632 | thing). |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 633 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 634 | ### Passing Parameters Owned By The Callback |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 635 | |
| 636 | ```cpp |
| 637 | void Foo(int* arg) { cout << *arg << endl; } |
| 638 | int* pn = new int(1); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 639 | base::Closure foo_callback = base::Bind(&foo, base::Owned(pn)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 640 | ``` |
| 641 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 642 | The parameter will be deleted when the callback is destroyed, even if it's not |
| 643 | run (like if you post a task during shutdown). |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 644 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 645 | ### Passing Parameters As A unique_ptr |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 646 | |
| 647 | ```cpp |
| 648 | void TakesOwnership(std::unique_ptr<Foo> arg) {} |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 649 | auto f = std::make_unique<Foo>(); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 650 | // f becomes null during the following call. |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 651 | base::OnceClosure cb = base::BindOnce(&TakesOwnership, std::move(f)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 652 | ``` |
| 653 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 654 | Ownership of the parameter will be with the callback until the callback is run, |
| 655 | and then ownership is passed to the callback function. This means the callback |
| 656 | can only be run once. If the callback is never run, it will delete the object |
| 657 | when it's destroyed. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 658 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 659 | ### Passing Parameters As A scoped_refptr |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 660 | |
| 661 | ```cpp |
| 662 | void TakesOneRef(scoped_refptr<Foo> arg) {} |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 663 | scoped_refptr<Foo> f(new Foo); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 664 | base::Closure cb = base::Bind(&TakesOneRef, f); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 665 | ``` |
| 666 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 667 | This should "just work." The closure will take a reference as long as it is |
| 668 | alive, and another reference will be taken for the called function. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 669 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 670 | ```cpp |
| 671 | void DontTakeRef(Foo* arg) {} |
| 672 | scoped_refptr<Foo> f(new Foo); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 673 | base::Closure cb = base::Bind(&DontTakeRef, base::RetainedRef(f)); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 674 | ``` |
| 675 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 676 | `base::RetainedRef` holds a reference to the object and passes a raw pointer to |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 677 | the object when the Callback is run. |
| 678 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 679 | ### Passing Parameters By Reference |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 680 | |
jdoerrie | 9d7236f6 | 2019-03-05 13:00:23 | [diff] [blame] | 681 | References are *copied* unless `std::ref` or `std::cref` is used. Example: |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 682 | |
| 683 | ```cpp |
| 684 | void foo(const int& arg) { printf("%d %p\n", arg, &arg); } |
| 685 | int n = 1; |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 686 | base::Closure has_copy = base::Bind(&foo, n); |
jdoerrie | 9d7236f6 | 2019-03-05 13:00:23 | [diff] [blame] | 687 | base::Closure has_ref = base::Bind(&foo, std::cref(n)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 688 | n = 2; |
| 689 | foo(n); // Prints "2 0xaaaaaaaaaaaa" |
| 690 | has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb" |
| 691 | has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa" |
| 692 | ``` |
| 693 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 694 | Normally parameters are copied in the closure. |
jdoerrie | 9d7236f6 | 2019-03-05 13:00:23 | [diff] [blame] | 695 | **DANGER**: `std::ref` and `std::cref` store a (const) reference instead, |
| 696 | referencing the original parameter. This means that you must ensure the object |
| 697 | outlives the callback! |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 698 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 699 | ## Implementation notes |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 700 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 701 | ### Where Is This Design From: |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 702 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 703 | The design of `base::Callback` and `base::Bind` is heavily influenced by C++'s |
| 704 | `tr1::function` / `tr1::bind`, and by the "Google Callback" system used inside |
| 705 | Google. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 706 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 707 | ### Customizing the behavior |
| 708 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 709 | There are several injection points that controls binding behavior from outside |
| 710 | of its implementation. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 711 | |
| 712 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 713 | namespace base { |
| 714 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 715 | template <typename Receiver> |
| 716 | struct IsWeakReceiver { |
| 717 | static constexpr bool value = false; |
| 718 | }; |
| 719 | |
| 720 | template <typename Obj> |
| 721 | struct UnwrapTraits { |
| 722 | template <typename T> |
| 723 | T&& Unwrap(T&& obj) { |
| 724 | return std::forward<T>(obj); |
| 725 | } |
| 726 | }; |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 727 | |
| 728 | } // namespace base |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 729 | ``` |
| 730 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 731 | If `base::IsWeakReceiver<Receiver>::value` is true on a receiver of a method, |
| 732 | `base::Bind` checks if the receiver is evaluated to true and cancels the invocation |
| 733 | if it's evaluated to false. You can specialize `base::IsWeakReceiver` to make |
| 734 | an external smart pointer as a weak pointer. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 735 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 736 | `base::UnwrapTraits<BoundObject>::Unwrap()` is called for each bound arguments |
jdoerrie | 9d7236f6 | 2019-03-05 13:00:23 | [diff] [blame] | 737 | right before `base::Callback` calls the target function. You can specialize this |
| 738 | to define an argument wrapper such as `base::Unretained`, `base::Owned`, |
| 739 | `base::RetainedRef` and `base::Passed`. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 740 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 741 | ### How The Implementation Works: |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 742 | |
| 743 | There are three main components to the system: |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 744 | 1) The `base::Callback<>` classes. |
| 745 | 2) The `base::Bind()` functions. |
jdoerrie | 9d7236f6 | 2019-03-05 13:00:23 | [diff] [blame] | 746 | 3) The arguments wrappers (e.g., `base::Unretained()` and `base::Owned()`). |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 747 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 748 | The Callback classes represent a generic function pointer. Internally, it |
| 749 | stores a refcounted piece of state that represents the target function and all |
| 750 | its bound parameters. The `base::Callback` constructor takes a |
| 751 | `base::BindStateBase*`, which is upcasted from a `base::BindState<>`. In the |
| 752 | context of the constructor, the static type of this `base::BindState<>` pointer |
| 753 | uniquely identifies the function it is representing, all its bound parameters, |
| 754 | and a `Run()` method that is capable of invoking the target. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 755 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 756 | `base::Bind()` creates the `base::BindState<>` that has the full static type, |
| 757 | and erases the target function type as well as the types of the bound |
| 758 | parameters. It does this by storing a pointer to the specific `Run()` function, |
| 759 | and upcasting the state of `base::BindState<>*` to a `base::BindStateBase*`. |
| 760 | This is safe as long as this `BindStateBase` pointer is only used with the |
| 761 | stored `Run()` pointer. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 762 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 763 | To `base::BindState<>` objects are created inside the `base::Bind()` functions. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 764 | These functions, along with a set of internal templates, are responsible for |
| 765 | |
| 766 | - Unwrapping the function signature into return type, and parameters |
| 767 | - Determining the number of parameters that are bound |
| 768 | - Creating the BindState storing the bound parameters |
| 769 | - Performing compile-time asserts to avoid error-prone behavior |
Armando Miraglia | cce1eb4 | 2018-08-16 14:35:44 | [diff] [blame] | 770 | - Returning a `Callback<>` with an arity matching the number of unbound |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 771 | parameters and that knows the correct refcounting semantics for the |
| 772 | target object if we are binding a method. |
| 773 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 774 | The `base::Bind` functions do the above using type-inference and variadic |
| 775 | templates. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 776 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 777 | By default `base::Bind()` will store copies of all bound parameters, and |
| 778 | attempt to refcount a target object if the function being bound is a class |
| 779 | method. These copies are created even if the function takes parameters as const |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 780 | references. (Binding to non-const references is forbidden, see bind.h.) |
| 781 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 782 | To change this behavior, we introduce a set of argument wrappers (e.g., |
jdoerrie | 9d7236f6 | 2019-03-05 13:00:23 | [diff] [blame] | 783 | `base::Unretained()`). These are simple container templates that are passed by |
danakj | db9ae794 | 2020-11-11 16:01:35 | [diff] [blame] | 784 | value, and wrap a pointer to argument. Each helper has a comment describing it |
| 785 | in base/bind.h. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 786 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 787 | These types are passed to the `Unwrap()` functions to modify the behavior of |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 788 | `base::Bind()`. The `Unwrap()` functions change behavior by doing partial |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 789 | specialization based on whether or not a parameter is a wrapper type. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 790 | |
jdoerrie | 9d7236f6 | 2019-03-05 13:00:23 | [diff] [blame] | 791 | `base::Unretained()` is specific to Chromium. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 792 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 793 | ### Missing Functionality |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 794 | - Binding arrays to functions that take a non-const pointer. |
| 795 | Example: |
| 796 | ```cpp |
| 797 | void Foo(const char* ptr); |
| 798 | void Bar(char* ptr); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 799 | base::Bind(&Foo, "test"); |
| 800 | base::Bind(&Bar, "test"); // This fails because ptr is not const. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 801 | ``` |
Gayane Petrosyan | 7f71698 | 2018-03-09 15:17:34 | [diff] [blame] | 802 | - In case of partial binding of parameters a possibility of having unbound |
| 803 | parameters before bound parameters. Example: |
| 804 | ```cpp |
| 805 | void Foo(int x, bool y); |
| 806 | base::Bind(&Foo, _1, false); // _1 is a placeholder. |
| 807 | ``` |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 808 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 809 | If you are thinking of forward declaring `base::Callback` in your own header |
| 810 | file, please include "base/callback_forward.h" instead. |