blob: c0dabf4c5bf7ce1d1000af82477fe7c03fe250f9 [file] [log] [blame] [view]
Colin Blundellea615d422021-05-12 09:35:411# OnceCallback<> and BindOnce(), RepeatingCallback<> and BindRepeating()
tzik703f1562016-09-02 07:36:552
Raphael Kubo da Costa17c1618c2019-03-28 19:30:443[TOC]
4
tzika4313512016-09-06 06:51:125## Introduction
tzik703f1562016-09-02 07:36:556
Colin Blundellea615d422021-05-12 09:35:417The templated `base::{Once, Repeating}Callback<>` classes are generalized
8function objects. Together with the `base::Bind{Once, Repeating}()` functions in
9base/bind.h, they provide a type-safe method for performing partial application
10of functions.
tzik703f1562016-09-02 07:36:5511
Matt Giuca7e81b22e2019-12-12 02:41:2112Partial application is the process of binding a subset of a function's arguments
13to produce another function that takes fewer arguments. This can be used to pass
14around a unit of delayed execution, much like lexical closures are used in other
15languages. For example, it is used in Chromium code to schedule tasks on
16different MessageLoops.
tzik703f1562016-09-02 07:36:5517
Colin Blundellea615d422021-05-12 09:35:4118A callback with no unbound input parameters (`base::OnceCallback<void()>`) is
19called a `base::OnceClosure`. The same pattern exists for
20base::RepeatingCallback, as base::RepeatingClosure. Note that this is NOT the
21same as what other languages refer to as a closure -- it does not retain a
22reference to its enclosing environment.
tzik703f1562016-09-02 07:36:5523
tzik7c0c0cf12016-10-05 08:14:0524### OnceCallback<> And RepeatingCallback<>
25
Brett Wilson508162c2017-09-27 22:24:4626`base::OnceCallback<>` is created by `base::BindOnce()`. This is a callback
27variant that is a move-only type and can be run only once. This moves out bound
28parameters from its internal storage to the bound function by default, so it's
29easier to use with movable types. This should be the preferred callback type:
30since the lifetime of the callback is clear, it's simpler to reason about when
31a callback that is passed between threads is destroyed.
tzik7c0c0cf12016-10-05 08:14:0532
Brett Wilson508162c2017-09-27 22:24:4633`base::RepeatingCallback<>` is created by `base::BindRepeating()`. This is a
34callback variant that is copyable that can be run multiple times. It uses
35internal ref-counting to make copies cheap. However, since ownership is shared,
36it is harder to reason about when the callback and the bound state are
37destroyed, especially when the callback is passed between threads.
tzik7c0c0cf12016-10-05 08:14:0538
Colin Blundellea615d422021-05-12 09:35:4139Prefer `base::OnceCallback<>` where possible, and use `base::RepeatingCallback<>`
40otherwise.
tzik7c0c0cf12016-10-05 08:14:0541
Brett Wilson508162c2017-09-27 22:24:4642`base::RepeatingCallback<>` is convertible to `base::OnceCallback<>` by the
43implicit conversion.
tzik7c0c0cf12016-10-05 08:14:0544
tzika4313512016-09-06 06:51:1245### Memory Management And Passing
tzik703f1562016-09-02 07:36:5546
danakje26d7cf2019-05-29 20:04:1447Pass `base::{Once,Repeating}Callback` objects by value if ownership is
48transferred; otherwise, pass it by const-reference.
tzik703f1562016-09-02 07:36:5549
tzik7c0c0cf12016-10-05 08:14:0550```cpp
51// |Foo| just refers to |cb| but doesn't store it nor consume it.
Brett Wilson508162c2017-09-27 22:24:4652bool Foo(const base::OnceCallback<void(int)>& cb) {
tzik7c0c0cf12016-10-05 08:14:0553 return cb.is_null();
54}
55
56// |Bar| takes the ownership of |cb| and stores |cb| into |g_cb|.
danakje26d7cf2019-05-29 20:04:1457base::RepeatingCallback<void(int)> g_cb;
58void Bar(base::RepeatingCallback<void(int)> cb) {
tzik7c0c0cf12016-10-05 08:14:0559 g_cb = std::move(cb);
60}
61
62// |Baz| takes the ownership of |cb| and consumes |cb| by Run().
Brett Wilson508162c2017-09-27 22:24:4663void Baz(base::OnceCallback<void(int)> cb) {
tzik7c0c0cf12016-10-05 08:14:0564 std::move(cb).Run(42);
65}
66
67// |Qux| takes the ownership of |cb| and transfers ownership to PostTask(),
68// which also takes the ownership of |cb|.
danakje26d7cf2019-05-29 20:04:1469void Qux(base::RepeatingCallback<void(int)> cb) {
70 PostTask(FROM_HERE, base::BindOnce(cb, 42));
71 PostTask(FROM_HERE, base::BindOnce(std::move(cb), 43));
tzik7c0c0cf12016-10-05 08:14:0572}
73```
74
danakje26d7cf2019-05-29 20:04:1475When you pass a `base::{Once,Repeating}Callback` object to a function parameter,
76use `std::move()` if you don't need to keep a reference to it, otherwise, pass the
Brett Wilson508162c2017-09-27 22:24:4677object directly. You may see a compile error when the function requires the
78exclusive ownership, and you didn't pass the callback by move. Note that the
danakje26d7cf2019-05-29 20:04:1479moved-from `base::{Once,Repeating}Callback` becomes null, as if its `Reset()`
80method had been called. Afterward, its `is_null()` method will return true and
81its `operator bool()` will return false.
tzik703f1562016-09-02 07:36:5582
danakjfcc5e7c2020-10-23 17:43:2783### Chaining callbacks
84
85When you have 2 callbacks that you wish to run in sequence, they can be joined
86together into a single callback through the use of `Then()`.
87
88Calling `Then()` on a `base::OnceCallback` joins a second callback that will be
89run together with, but after, the first callback. The return value from the
90first callback is passed along to the second, and the return value from the
91second callback is returned at the end. More concretely, calling `a.Then(b)`
92produces a new `base::OnceCallback` that will run `b(a());`, returning the
93result from `b`.
94
95This example uses `Then()` to join 2 `base::OnceCallback`s together:
96```cpp
97int Floor(float f) { return std::floor(f); }
98std::string IntToString(int i) { return base::NumberToString(i); }
99
100base::OnceCallback<int(float)> first = base::BindOnce(&Floor);
101base::OnceCallback<std::string(int)> second = base::BindOnce(&IntToString);
102
103// This will run |first|, run and pass the result to |second|, then return
104// the result from |second|.
105std::string r = std::move(first).Then(std::move(second)).Run(3.5f);
106// |r| will be "3". |first| and |second| are now both null, as they were
107// consumed to perform the join operation.
108```
109
110Similarly, `Then()` also works with `base::RepeatingCallback`; however, the
111joined callback must also be a `base::RepeatingCallback` to ensure the resulting
112callback can be invoked multiple times.
113
114This example uses `Then()` to join 2 `base::RepeatingCallback`s together:
115```cpp
116int Floor(float f) { return std::floor(f); }
117std::string IntToString(int i) { return base::NumberToString(i); }
118
119base::RepeatingCallback<int(float)> first = base::BindRepeating(&Floor);
120base::RepeatingCallback<std::string(int)> second = base::BindRepeating(&IntToString);
121
122// This creates a RepeatingCallback that will run |first|, run and pass the
123// result to |second|, then return the result from |second|.
124base::RepeatingCallback<std::string(float)> joined =
125 std::move(first).Then(std::move(second));
126// |first| and |second| are now both null, as they were consumed to perform
127// the join operation.
128
129// This runs the functor that was originally bound to |first|, then |second|.
130std::string r = joined.Run(3.5);
131// |r| will be "3".
132
133// It's valid to call it multiple times since all callbacks involved are
134// base::RepeatingCallbacks.
135r = joined.Run(2.5);
136// |r| is set to "2".
137```
138
139In the above example, casting the `base::RepeatingCallback` to an r-value with
140`std::move()` causes `Then()` to destroy the original callback, in the same way
141that occurs for joining `base::OnceCallback`s. However since a
142`base::RepeatingCallback` can be run multiple times, it can be joined
143non-destructively as well.
144```cpp
145int Floor(float f) { return std::floor(f); }
146std::string IntToString(int i) { return base::NumberToString(i); }
147
148base::RepeatingCallback<int(float)> first = base::BindRepeating(&Floor);
149base::RepeatingCallback<std::string(int)> second = base::BindRepeating(&IntToString);
150
151// This creates a RepeatingCallback that will run |first|, run and pass the
152// result to |second|, then return the result from |second|.
153std::string r = first.Then(second).Run(3.5f);
154// |r| will be 3, and |first| and |second| are still valid to use.
155
156// Runs Floor().
157int i = first.Run(5.5);
158// Runs IntToString().
159std::string s = second.Run(9);
160```
161
danakj9335cb1c2020-10-28 20:21:21162If the second callback does not want to receive a value from the first callback,
163you may use `base::IgnoreResult` to drop the return value in between running the
164two.
165
166```cpp
167// Returns an integer.
168base::RepeatingCallback<int()> first = base::BindRepeating([](){ return 5; });
169// Does not want to receive an integer.
170base::RepeatingClosure second = base::BindRepeating([](){});
171
172// This will not compile, because |second| can not receive the return value from
173// |first|.
174// first.Then(second).Run();
175
176// We can drop the result from |first| before running second.
177base::BindRepeating(base::IgnoreResult(first)).Then(second).Run();
178// This will effectively create a callback that when Run() will call
179// `first(); second();` instead of `second(first());`.
180```
181
182Note that the return value from |first| will be lost in the above example, and
183would be destroyed before |second| is run. If you want the return value from
184|first| to be preserved and ultimately returned after running both |first| and
185|second|, then you would need a primitive such as the `base::PassThrough<T>()`
186helper in the [base::PassThrough CL](https://chromium-review.googlesource.com/c/chromium/src/+/2493243).
187If this would be helpful for you, please let [email protected] know or ping
188the CL.
189
kylechardde7d232020-11-16 17:35:09190### Chaining callbacks across different task runners
191
192```cpp
193// The task runner for a different thread.
194scoped_refptr<base::SequencedTaskRunner> other_task_runner = ...;
195
196// A function to compute some interesting result, except it can only be run
197// safely from `other_task_runner` and not the current thread.
198int ComputeResult();
199
200base::OnceCallback<int()> compute_result_cb = base::BindOnce(&ComputeResult);
201
202// Task runner for the current thread.
203scoped_refptr<base::SequencedTaskRunner> current_task_runner =
204 base::SequencedTaskRunnerHandle::Get();
205
206// A function to accept the result, except it can only be run safely from the
207// current thread.
208void ProvideResult(int result);
209
210base::OnceCallback<void(int)> provide_result_cb =
211 base::BindOnce(&ProvideResult);
212```
213
214Using `Then()` to join `compute_result_cb` and `provide_result_cb` directly
215would be inappropriate. `ComputeResult()` and `ProvideResult()` would run on the
216same thread which isn't safe. However, `base::BindPostTask()` can be used to
217ensure `provide_result_cb` will run on `current_task_runner`.
218
219```cpp
220// The following two statements post a task to `other_task_runner` to run
221// `task`. This will invoke ComputeResult() on a different thread to get the
222// result value then post a task back to `current_task_runner` to invoke
223// ProvideResult() with the result.
224OnceClosure task =
225 std::move(compute_result_cb)
226 .Then(base::BindPostTask(current_task_runner,
227 std::move(provide_result_cb)));
228other_task_runner->PostTask(FROM_HERE, std::move(task));
229```
230
Thomas Guilbert5db52382020-12-17 22:33:14231### Splitting a OnceCallback in two
232
233If a callback is only run once, but two references need to be held to the
234callback, using a `base::OnceCallback` can be clearer than a
235`base::RepeatingCallback`, from an intent and semantics point of view.
236`base::SplitOnceCallback()` takes a `base::OnceCallback` and returns a pair of
237callbacks with the same signature. When either of the returned callback is run,
238the original callback is invoked. Running the leftover callback will result in a
239crash.
240This can be useful when passing a `base::OnceCallback` to a function that may or
241may not take ownership of the callback. E.g, when an object creation could fail:
242
243```cpp
244std::unique_ptr<FooTask> CreateFooTask(base::OnceClosure task) {
245 std::pair<base::OnceClosure,base::OnceClosure> split
246 = base::SplitOnceCallback(std::move(task));
247
248 std::unique_ptr<FooTask> foo = TryCreateFooTask(std::move(split.first));
249 if (foo)
250 return foo;
251
252 return CreateFallbackFooTask(std::move(split.second));
253}
254```
255
256While it is best to use a single callback to report success/failure, some APIs
257already take multiple callbacks. `base::SplitOnceCallback()` can be used to
258split a completion callback and help in such a case:
259
260```cpp
261using StatusCallback = base::OnceCallback<void(FooStatus)>;
262void DoOperation(StatusCallback done_cb) {
263 std::pair<StatusCallback, StatusCallback> split
264 = base::SplitOnceCallback(std::move(done_cb));
265
266 InnerWork(BindOnce(std::move(split.first), STATUS_OK),
267 BindOnce(std::move(split.second), STATUS_ABORTED));
268}
269
270void InnerWork(base::OnceClosure work_done_cb,
271 base::OnceClosure work_aborted_cb);
272```
273
Roland Bock6269edb2022-01-04 19:34:15274### BarrierCallback<T>
275
276Sometimes you might need to request data from several sources, then do something
277with the collective results once all data is available. You can do this with a
278`BarrierCallback<T>`. The `BarrierCallback<T>` is created with two parameters:
279
280- `num_callbacks`: The number of times the `BarrierCallback` can be run, each
281 time being passed an object of type T.
282- `done_callback`: This will be run once the `BarrierCallback` has been run
283 `num_callbacks` times.
284
285The `done_callback` will receive a `std::vector<T>` containing the
286`num_callbacks` parameters passed in the respective `Run` calls. The order of
287`Ts` in the `vector` is unspecified.
288
289Note that
290
291- barrier callback must not be run more than `num_callback` times,
292- `done_callback` will be called on the same thread as the final call to the
293 barrier callback. `done_callback` will also be cleared on the same thread.
294
295Example:
296
297```cpp
298void Merge(const std::vector<Data>& data);
299
300void Collect(base::OnceCallback<void(Data)> collect_and_merge) {
301 // Do something, probably asynchronously, and at some point:
302 std::move(collect_and_merge).Run(data);
303}
304
305CollectAndMerge() {
306 const auto collect_and_merge =
307 base::BarrierCallback<Image>(sources_.size(), base::BindOnce(&Merge));
308 for (const auto& source : sources_) {
309 // Copy the barrier callback for asynchronous data collection.
310 // Once all sources have called `collect_and_merge` with their respective
311 // data, |Merge| will be called with a vector of the collected data.
312 source.Collect(collect_and_merge);
313 }
314}
315```
316
tzika4313512016-09-06 06:51:12317## Quick reference for basic stuff
tzik703f1562016-09-02 07:36:55318
tzika4313512016-09-06 06:51:12319### Binding A Bare Function
tzik703f1562016-09-02 07:36:55320
321```cpp
322int Return5() { return 5; }
Brett Wilson508162c2017-09-27 22:24:46323base::OnceCallback<int()> func_cb = base::BindOnce(&Return5);
tzik7c0c0cf12016-10-05 08:14:05324LOG(INFO) << std::move(func_cb).Run(); // Prints 5.
325```
326
327```cpp
328int Return5() { return 5; }
Brett Wilson508162c2017-09-27 22:24:46329base::RepeatingCallback<int()> func_cb = base::BindRepeating(&Return5);
tzik703f1562016-09-02 07:36:55330LOG(INFO) << func_cb.Run(); // Prints 5.
331```
332
tzik7c0c0cf12016-10-05 08:14:05333### Binding A Captureless Lambda
334
335```cpp
Colin Blundellea615d422021-05-12 09:35:41336base::RepeatingCallback<int()> lambda_cb = base::BindRepeating([] { return 4; });
tzik7c0c0cf12016-10-05 08:14:05337LOG(INFO) << lambda_cb.Run(); // Print 4.
338
Brett Wilson508162c2017-09-27 22:24:46339base::OnceCallback<int()> lambda_cb2 = base::BindOnce([] { return 3; });
tzik7c0c0cf12016-10-05 08:14:05340LOG(INFO) << std::move(lambda_cb2).Run(); // Print 3.
Erik Chen9425c0f2020-09-11 21:41:09341
342base::OnceCallback<int()> lambda_cb3 = base::BindOnce([] { return 2; });
343base::OnceCallback<int(base::OnceCallback<int()>)> lambda_cb4 =
344 base::BindOnce(
345 [](base::OnceCallback<int()> callback) {
346 return std::move(callback).Run(); },
347 std::move(lambda_cb3));
348LOG(INFO) << std::move(lambda_cb4).Run(); // Print 2.
349
tzik7c0c0cf12016-10-05 08:14:05350```
351
Raphael Kubo da Costa17c1618c2019-03-28 19:30:44352### Binding A Capturing Lambda (In Tests)
353
354When writing tests, it is often useful to capture arguments that need to be
355modified in a callback.
356
357``` cpp
Guido Urdanetaef4e91942020-11-09 15:06:24358#include "base/test/bind.h"
Raphael Kubo da Costa17c1618c2019-03-28 19:30:44359
360int i = 2;
Colin Blundellea615d422021-05-12 09:35:41361base::RepeatingCallback<void()> lambda_cb = base::BindLambdaForTesting([&]() { i++; });
Raphael Kubo da Costa17c1618c2019-03-28 19:30:44362lambda_cb.Run();
363LOG(INFO) << i; // Print 3;
364```
365
tzika4313512016-09-06 06:51:12366### Binding A Class Method
tzik703f1562016-09-02 07:36:55367
tzika4313512016-09-06 06:51:12368The first argument to bind is the member function to call, the second is the
369object on which to call it.
tzik703f1562016-09-02 07:36:55370
371```cpp
Brett Wilson508162c2017-09-27 22:24:46372class Ref : public base::RefCountedThreadSafe<Ref> {
tzik703f1562016-09-02 07:36:55373 public:
374 int Foo() { return 3; }
tzik703f1562016-09-02 07:36:55375};
376scoped_refptr<Ref> ref = new Ref();
Colin Blundellea615d422021-05-12 09:35:41377base::RepeatingCallback<void()> ref_cb = base::BindRepeating(&Ref::Foo, ref);
tzik703f1562016-09-02 07:36:55378LOG(INFO) << ref_cb.Run(); // Prints out 3.
379```
380
381By default the object must support RefCounted or you will get a compiler
tzik7c0c0cf12016-10-05 08:14:05382error. If you're passing between threads, be sure it's RefCountedThreadSafe! See
383"Advanced binding of member functions" below if you don't want to use reference
384counting.
tzik703f1562016-09-02 07:36:55385
tzika4313512016-09-06 06:51:12386### Running A Callback
tzik703f1562016-09-02 07:36:55387
tzik7c0c0cf12016-10-05 08:14:05388Callbacks can be run with their `Run` method, which has the same signature as
Brett Wilson508162c2017-09-27 22:24:46389the template argument to the callback. Note that `base::OnceCallback::Run`
390consumes the callback object and can only be invoked on a callback rvalue.
tzik703f1562016-09-02 07:36:55391
392```cpp
Colin Blundellea615d422021-05-12 09:35:41393void DoSomething(const base::RepeatingCallback<void(int, std::string)>& callback) {
tzik703f1562016-09-02 07:36:55394 callback.Run(5, "hello");
395}
tzik7c0c0cf12016-10-05 08:14:05396
Brett Wilson508162c2017-09-27 22:24:46397void DoSomethingOther(base::OnceCallback<void(int, std::string)> callback) {
tzik7c0c0cf12016-10-05 08:14:05398 std::move(callback).Run(5, "hello");
399}
tzik703f1562016-09-02 07:36:55400```
401
tzik7c0c0cf12016-10-05 08:14:05402RepeatingCallbacks can be run more than once (they don't get deleted or marked
Brett Wilson508162c2017-09-27 22:24:46403when run). However, this precludes using `base::Passed` (see below).
tzik703f1562016-09-02 07:36:55404
405```cpp
Brett Wilson508162c2017-09-27 22:24:46406void DoSomething(const base::RepeatingCallback<double(double)>& callback) {
tzik703f1562016-09-02 07:36:55407 double myresult = callback.Run(3.14159);
408 myresult += callback.Run(2.71828);
409}
410```
411
michaelpg0f156e12017-03-18 02:49:09412If running a callback could result in its own destruction (e.g., if the callback
413recipient deletes the object the callback is a member of), the callback should
Greg Thompsonddc84d42021-01-04 10:10:02414be moved or copied onto the stack before it can be safely invoked. (Note that
415this is only an issue for RepeatingCallbacks, because a OnceCallback always has
416to be moved for execution.)
michaelpg0f156e12017-03-18 02:49:09417
418```cpp
419void Foo::RunCallback() {
Bence Béky15327452018-05-10 20:59:07420 std::move(&foo_deleter_callback_).Run();
michaelpg0f156e12017-03-18 02:49:09421}
422```
423
Peter Kasting341e1fb2018-02-24 00:03:01424### Creating a Callback That Does Nothing
425
426Sometimes you need a callback that does nothing when run (e.g. test code that
427doesn't care to be notified about certain types of events). It may be tempting
428to pass a default-constructed callback of the right type:
429
430```cpp
431using MyCallback = base::OnceCallback<void(bool arg)>;
432void MyFunction(MyCallback callback) {
433 std::move(callback).Run(true); // Uh oh...
434}
435...
436MyFunction(MyCallback()); // ...this will crash when Run()!
437```
438
439Default-constructed callbacks are null, and thus cannot be Run(). Instead, use
440`base::DoNothing()`:
441
442```cpp
443...
444MyFunction(base::DoNothing()); // Can be Run(), will no-op
445```
446
447`base::DoNothing()` can be passed for any OnceCallback or RepeatingCallback that
448returns void.
449
450Implementation-wise, `base::DoNothing()` is actually a functor which produces a
451callback from `operator()`. This makes it unusable when trying to bind other
452arguments to it. Normally, the only reason to bind arguments to DoNothing() is
453to manage object lifetimes, and in these cases, you should strive to use idioms
454like DeleteSoon(), ReleaseSoon(), or RefCountedDeleteOnSequence instead. If you
455truly need to bind an argument to DoNothing(), or if you need to explicitly
456create a callback object (because implicit conversion through operator()() won't
457compile), you can instantiate directly:
458
459```cpp
460// Binds |foo_ptr| to a no-op OnceCallback takes a scoped_refptr<Foo>.
461// ANTIPATTERN WARNING: This should likely be changed to ReleaseSoon()!
Dmitrii Kuragin2e7da8652022-06-14 20:17:21462base::BindOnce(base::DoNothingAs<void(scoped_refptr<Foo>)>(), foo_ptr);
Peter Kasting341e1fb2018-02-24 00:03:01463```
464
tzika4313512016-09-06 06:51:12465### Passing Unbound Input Parameters
tzik703f1562016-09-02 07:36:55466
467Unbound parameters are specified at the time a callback is `Run()`. They are
Colin Blundellea615d422021-05-12 09:35:41468specified in the `base::{Once, Repeating}Callback` template type:
tzik703f1562016-09-02 07:36:55469
470```cpp
471void MyFunc(int i, const std::string& str) {}
Colin Blundellea615d422021-05-12 09:35:41472base::RepeatingCallback<void(int, const std::string&)> cb = base::BindRepeating(&MyFunc);
tzik703f1562016-09-02 07:36:55473cb.Run(23, "hello, world");
474```
475
tzika4313512016-09-06 06:51:12476### Passing Bound Input Parameters
tzik703f1562016-09-02 07:36:55477
tzika4313512016-09-06 06:51:12478Bound parameters are specified when you create the callback as arguments to
Colin Blundellea615d422021-05-12 09:35:41479`base::Bind{Once, Repeating}()`. They will be passed to the function and the `Run()`ner of the
Brett Wilson508162c2017-09-27 22:24:46480callback doesn't see those values or even know that the function it's calling.
tzik703f1562016-09-02 07:36:55481
482```cpp
483void MyFunc(int i, const std::string& str) {}
Colin Blundellea615d422021-05-12 09:35:41484base::RepeatingCallback<void()> cb = base::BindRepeating(&MyFunc, 23, "hello world");
tzik703f1562016-09-02 07:36:55485cb.Run();
486```
487
Colin Blundellea615d422021-05-12 09:35:41488As described earlier, a callback with no unbound input parameters
489(`base::RepeatingCallback<void()>`) is called a `base::RepeatingClosure`. So we
490could have also written:
tzik703f1562016-09-02 07:36:55491
492```cpp
Colin Blundellea615d422021-05-12 09:35:41493base::RepeatingClosure cb = base::BindRepeating(&MyFunc, 23, "hello world");
tzik703f1562016-09-02 07:36:55494```
495
496When calling member functions, bound parameters just go after the object
497pointer.
498
499```cpp
Colin Blundellea615d422021-05-12 09:35:41500base::RepeatingClosure cb = base::BindRepeating(&MyClass::MyFunc, this, 23, "hello world");
tzik703f1562016-09-02 07:36:55501```
502
Matt Giuca7e81b22e2019-12-12 02:41:21503### Partial Binding Of Parameters
tzik703f1562016-09-02 07:36:55504
tzika4313512016-09-06 06:51:12505You can specify some parameters when you create the callback, and specify the
506rest when you execute the callback.
tzik703f1562016-09-02 07:36:55507
tzik703f1562016-09-02 07:36:55508When calling a function bound parameters are first, followed by unbound
509parameters.
510
Gabriel Charette90480312018-02-16 15:10:05511```cpp
512void ReadIntFromFile(const std::string& filename,
513 base::OnceCallback<void(int)> on_read);
514
515void DisplayIntWithPrefix(const std::string& prefix, int result) {
516 LOG(INFO) << prefix << result;
517}
518
519void AnotherFunc(const std::string& file) {
520 ReadIntFromFile(file, base::BindOnce(&DisplayIntWithPrefix, "MyPrefix: "));
521};
522```
523
Matt Giuca7e81b22e2019-12-12 02:41:21524This technique is known as [partial
525application](http://en.wikipedia.org/wiki/Partial_application). It should be
526used in lieu of creating an adapter class that holds the bound arguments. Notice
527also that the `"MyPrefix: "` argument is actually a `const char*`, while
528`DisplayIntWithPrefix` actually wants a `const std::string&`. Like normal
529function dispatch, `base::Bind`, will coerce parameter types if possible.
Gabriel Charette90480312018-02-16 15:10:05530
Max Morinb51cf512018-02-19 12:49:49531### Avoiding Copies With Callback Parameters
tzik7c0c0cf12016-10-05 08:14:05532
Max Morinb51cf512018-02-19 12:49:49533A parameter of `base::BindRepeating()` or `base::BindOnce()` is moved into its
534internal storage if it is passed as a rvalue.
tzik7c0c0cf12016-10-05 08:14:05535
536```cpp
537std::vector<int> v = {1, 2, 3};
538// |v| is moved into the internal storage without copy.
Colin Blundellea615d422021-05-12 09:35:41539base::BindOnce(&Foo, std::move(v));
tzik7c0c0cf12016-10-05 08:14:05540```
541
542```cpp
tzik7c0c0cf12016-10-05 08:14:05543// The vector is moved into the internal storage without copy.
Colin Blundellea615d422021-05-12 09:35:41544base::BindOnce(&Foo, std::vector<int>({1, 2, 3}));
tzik7c0c0cf12016-10-05 08:14:05545```
546
Max Morinb51cf512018-02-19 12:49:49547Arguments bound with `base::BindOnce()` are always moved, if possible, to the
548target function.
549A function parameter that is passed by value and has a move constructor will be
550moved instead of copied.
551This makes it easy to use move-only types with `base::BindOnce()`.
552
553In contrast, arguments bound with `base::BindRepeating()` are only moved to the
554target function if the argument is bound with `base::Passed()`.
555
556**DANGER**:
557A `base::RepeatingCallback` can only be run once if arguments were bound with
558`base::Passed()`.
559For this reason, avoid `base::Passed()`.
560If you know a callback will only be called once, prefer to refactor code to
561work with `base::OnceCallback` instead.
562
563Avoid using `base::Passed()` with `base::BindOnce()`, as `std::move()` does the
564same thing and is more familiar.
tzik7c0c0cf12016-10-05 08:14:05565
566```cpp
567void Foo(std::unique_ptr<int>) {}
Max Morinb51cf512018-02-19 12:49:49568auto p = std::make_unique<int>(42);
tzik7c0c0cf12016-10-05 08:14:05569
Colin Blundellea615d422021-05-12 09:35:41570// |p| is moved into the internal storage of BindOnce(), and moved out to |Foo|.
Brett Wilson508162c2017-09-27 22:24:46571base::BindOnce(&Foo, std::move(p));
Max Morinb51cf512018-02-19 12:49:49572base::BindRepeating(&Foo, base::Passed(&p)); // Ok, but subtle.
573base::BindRepeating(&Foo, base::Passed(std::move(p))); // Ok, but subtle.
tzik7c0c0cf12016-10-05 08:14:05574```
575
tzika4313512016-09-06 06:51:12576## Quick reference for advanced binding
tzik703f1562016-09-02 07:36:55577
tzika4313512016-09-06 06:51:12578### Binding A Class Method With Weak Pointers
tzik703f1562016-09-02 07:36:55579
Wez33276262019-06-21 00:11:20580If `MyClass` has a `base::WeakPtr<MyClass> weak_this_` member (see below)
581then a class method can be bound with:
582
tzik703f1562016-09-02 07:36:55583```cpp
Colin Blundellea615d422021-05-12 09:35:41584base::BindOnce(&MyClass::Foo, weak_this_);
tzika4313512016-09-06 06:51:12585```
tzik703f1562016-09-02 07:36:55586
587The callback will not be run if the object has already been destroyed.
Brett Wilson508162c2017-09-27 22:24:46588
Wez33276262019-06-21 00:11:20589Note that class method callbacks bound to `base::WeakPtr`s may only be
590run on the same sequence on which the object will be destroyed, since otherwise
591execution of the callback might race with the object's deletion.
592
Colin Blundellea615d422021-05-12 09:35:41593To use `base::WeakPtr` with `base::Bind{Once, Repeating}()` as the `this`
594pointer to a method bound in a callback, `MyClass` will typically look like:
Wez33276262019-06-21 00:11:20595
596```cpp
597class MyClass {
598public:
Jeremy Roman0dd0b2f2019-07-16 21:00:43599 MyClass() {
Wez33276262019-06-21 00:11:20600 weak_this_ = weak_factory_.GetWeakPtr();
601 }
602private:
603 base::WeakPtr<MyClass> weak_this_;
604 // MyClass member variables go here.
Jeremy Roman0dd0b2f2019-07-16 21:00:43605 base::WeakPtrFactory<MyClass> weak_factory_{this};
Wez33276262019-06-21 00:11:20606};
607```
608
609`weak_factory_` is the last member variable in `MyClass` so that it is
610destroyed first. This ensures that if any class methods bound to `weak_this_`
611are `Run()` during teardown, then they will not actually be executed.
612
Colin Blundellea615d422021-05-12 09:35:41613If `MyClass` only ever binds and executes callbacks on the same sequence, then
614it is generally safe to call `weak_factory_.GetWeakPtr()` at the
615`base::Bind{Once, Repeating}()` call, rather than taking a separate `weak_this_`
616during construction.
tzik703f1562016-09-02 07:36:55617
tzika4313512016-09-06 06:51:12618### Binding A Class Method With Manual Lifetime Management
tzik703f1562016-09-02 07:36:55619
620```cpp
Colin Blundellea615d422021-05-12 09:35:41621base::BindOnce(&MyClass::Foo, base::Unretained(this));
tzik703f1562016-09-02 07:36:55622```
623
tzika4313512016-09-06 06:51:12624This disables all lifetime management on the object. You're responsible for
625making sure the object is alive at the time of the call. You break it, you own
626it!
tzik703f1562016-09-02 07:36:55627
tzika4313512016-09-06 06:51:12628### Binding A Class Method And Having The Callback Own The Class
tzik703f1562016-09-02 07:36:55629
630```cpp
631MyClass* myclass = new MyClass;
Colin Blundellea615d422021-05-12 09:35:41632base::BindOnce(&MyClass::Foo, base::Owned(myclass));
tzik703f1562016-09-02 07:36:55633```
634
tzika4313512016-09-06 06:51:12635The object will be deleted when the callback is destroyed, even if it's not run
636(like if you post a task during shutdown). Potentially useful for "fire and
637forget" cases.
tzik703f1562016-09-02 07:36:55638
tzik7c0c0cf12016-10-05 08:14:05639Smart pointers (e.g. `std::unique_ptr<>`) are also supported as the receiver.
640
641```cpp
642std::unique_ptr<MyClass> myclass(new MyClass);
Colin Blundellea615d422021-05-12 09:35:41643base::BindOnce(&MyClass::Foo, std::move(myclass));
tzik7c0c0cf12016-10-05 08:14:05644```
645
tzika4313512016-09-06 06:51:12646### Ignoring Return Values
tzik703f1562016-09-02 07:36:55647
tzika4313512016-09-06 06:51:12648Sometimes you want to call a function that returns a value in a callback that
649doesn't expect a return value.
tzik703f1562016-09-02 07:36:55650
651```cpp
Wen Fandd472022021-03-12 01:31:09652int DoSomething(int arg) {
653 cout << arg << endl;
654 return arg;
655}
danakj9335cb1c2020-10-28 20:21:21656base::RepeatingCallback<void(int)> cb =
657 base::BindRepeating(IgnoreResult(&DoSomething));
658```
659
660Similarly, you may want to use an existing callback that returns a value in a
661place that expects a void return type.
662
663```cpp
664base::RepeatingCallback<int()> cb = base::BindRepeating([](){ return 5; });
665base::RepeatingClosure void_cb = base::BindRepeating(base::IgnoreResult(cb));
tzik703f1562016-09-02 07:36:55666```
667
Colin Blundellea615d422021-05-12 09:35:41668## Quick reference for binding parameters to BindOnce() and BindRepeating()
tzik703f1562016-09-02 07:36:55669
Colin Blundellea615d422021-05-12 09:35:41670Bound parameters are specified as arguments to `base::Bind{Once, Repeating}()`
671and are passed to the functions.
tzik703f1562016-09-02 07:36:55672
tzika4313512016-09-06 06:51:12673### Passing Parameters Owned By The Callback
tzik703f1562016-09-02 07:36:55674
675```cpp
676void Foo(int* arg) { cout << *arg << endl; }
677int* pn = new int(1);
Colin Blundellea615d422021-05-12 09:35:41678base::RepeatingClosure foo_callback = base::BindRepeating(&foo, base::Owned(pn));
tzik703f1562016-09-02 07:36:55679```
680
tzika4313512016-09-06 06:51:12681The parameter will be deleted when the callback is destroyed, even if it's not
682run (like if you post a task during shutdown).
tzik703f1562016-09-02 07:36:55683
tzika4313512016-09-06 06:51:12684### Passing Parameters As A unique_ptr
tzik703f1562016-09-02 07:36:55685
686```cpp
687void TakesOwnership(std::unique_ptr<Foo> arg) {}
Max Morinb51cf512018-02-19 12:49:49688auto f = std::make_unique<Foo>();
tzik703f1562016-09-02 07:36:55689// f becomes null during the following call.
Max Morinb51cf512018-02-19 12:49:49690base::OnceClosure cb = base::BindOnce(&TakesOwnership, std::move(f));
tzik703f1562016-09-02 07:36:55691```
692
tzika4313512016-09-06 06:51:12693Ownership of the parameter will be with the callback until the callback is run,
694and then ownership is passed to the callback function. This means the callback
695can only be run once. If the callback is never run, it will delete the object
696when it's destroyed.
tzik703f1562016-09-02 07:36:55697
tzika4313512016-09-06 06:51:12698### Passing Parameters As A scoped_refptr
tzik703f1562016-09-02 07:36:55699
700```cpp
701void TakesOneRef(scoped_refptr<Foo> arg) {}
tzik7c0c0cf12016-10-05 08:14:05702scoped_refptr<Foo> f(new Foo);
Colin Blundellea615d422021-05-12 09:35:41703base::RepeatingClosure cb = base::BindRepeating(&TakesOneRef, f);
tzik703f1562016-09-02 07:36:55704```
705
tzika4313512016-09-06 06:51:12706This should "just work." The closure will take a reference as long as it is
707alive, and another reference will be taken for the called function.
tzik703f1562016-09-02 07:36:55708
tzik7c0c0cf12016-10-05 08:14:05709```cpp
710void DontTakeRef(Foo* arg) {}
711scoped_refptr<Foo> f(new Foo);
Colin Blundellea615d422021-05-12 09:35:41712base::RepeatingClosure cb = base::BindRepeating(&DontTakeRef, base::RetainedRef(f));
tzik7c0c0cf12016-10-05 08:14:05713```
714
Brett Wilson508162c2017-09-27 22:24:46715`base::RetainedRef` holds a reference to the object and passes a raw pointer to
tzik7c0c0cf12016-10-05 08:14:05716the object when the Callback is run.
717
kylechar72e6f782021-03-17 17:43:38718### Binding Const Reference Parameters
tzik703f1562016-09-02 07:36:55719
kylechar72e6f782021-03-17 17:43:38720If the callback function takes a const reference parameter then the value is
721*copied* when bound unless `std::ref` or `std::cref` is used. Example:
tzik703f1562016-09-02 07:36:55722
723```cpp
724void foo(const int& arg) { printf("%d %p\n", arg, &arg); }
725int n = 1;
kylechar72e6f782021-03-17 17:43:38726base::OnceClosure has_copy = base::BindOnce(&foo, n);
727base::OnceClosure has_ref = base::BindOnce(&foo, std::cref(n));
tzik703f1562016-09-02 07:36:55728n = 2;
kylechar72e6f782021-03-17 17:43:38729foo(n); // Prints "2 0xaaaaaaaaaaaa"
730std::move(has_copy).Run(); // Prints "1 0xbbbbbbbbbbbb"
731std::move(has_ref).Run(); // Prints "2 0xaaaaaaaaaaaa"
tzik703f1562016-09-02 07:36:55732```
733
kylechar72e6f782021-03-17 17:43:38734Normally parameters are copied in the closure. **DANGER**: `std::ref` and
735`std::cref` store a (const) reference instead, referencing the original
736parameter. This means that you must ensure the object outlives the callback!
737
738### Binding Non-Const Reference Parameters
739
740If the callback function takes a non-const reference then the bind statement
741must specify what behavior is desired. If a reference that can mutate the
742original value is desired then `std::ref` is used. If the callback should take
743ownership of the value, either by making a copy or moving an existing value,
744then `base::OwnedRef` is used. If neither is used the bind statement will fail
745to compile. Example:
746
747```cpp
748void foo(int& arg) {
749 printf("%d\n", arg);
750 ++arg;
751}
752
753int n = 0;
754base::RepeatingClosure has_ref = base::BindRepeating(&foo, std::ref(n));
755base::RepeatingClosure has_copy = base::BindRepeating(&foo, base::OwnedRef(n));
756
757foo(n); // Prints "0"
758has_ref.Run(); // Prints "1"
759has_ref.Run(); // Prints "2"
760foo(n); // Prints "3"
761
762has_copy.Run(); // Prints "0"
763has_copy.Run(); // Prints "1"
764
765// This will fail to compile.
766base::RepeatingClosure cb = base::BindRepeating(&foo, n);
767```
768
769Normally parameters are copied in the closure. **DANGER**: `std::ref` stores a
770reference instead, referencing the original parameter. This means that you must
771ensure the object outlives the callback!
772
773If the callback function has an output reference parameter but the output value
774isn't needed then `base::OwnedRef()` is a convenient way to handle it. The
775callback owned value will be mutated by the callback function and then deleted
776along with the callback. Example:
777
778```cpp
779bool Compute(size_t index, int& output);
780
781// The `output` parameter isn't important for the callback, it only cares about
782// the return value.
783base::OnceClosure cb = base::BindOnce(&Compute, index, base::OwnedRef(0));
784bool success = std::move(cb).Run();
785```
tzik703f1562016-09-02 07:36:55786
tzika4313512016-09-06 06:51:12787## Implementation notes
tzik703f1562016-09-02 07:36:55788
tzika4313512016-09-06 06:51:12789### Where Is This Design From:
tzik703f1562016-09-02 07:36:55790
Colin Blundellea615d422021-05-12 09:35:41791The design is heavily influenced by C++'s `tr1::function` / `tr1::bind`, and by
792the "Google Callback" system used inside Google.
tzik703f1562016-09-02 07:36:55793
tzik7c0c0cf12016-10-05 08:14:05794### Customizing the behavior
795
Brett Wilson508162c2017-09-27 22:24:46796There are several injection points that controls binding behavior from outside
797of its implementation.
tzik7c0c0cf12016-10-05 08:14:05798
799```cpp
Brett Wilson508162c2017-09-27 22:24:46800namespace base {
801
tzik7c0c0cf12016-10-05 08:14:05802template <typename Receiver>
803struct IsWeakReceiver {
804 static constexpr bool value = false;
805};
806
807template <typename Obj>
808struct UnwrapTraits {
809 template <typename T>
810 T&& Unwrap(T&& obj) {
811 return std::forward<T>(obj);
812 }
813};
Brett Wilson508162c2017-09-27 22:24:46814
815} // namespace base
tzik7c0c0cf12016-10-05 08:14:05816```
817
Brett Wilson508162c2017-09-27 22:24:46818If `base::IsWeakReceiver<Receiver>::value` is true on a receiver of a method,
819`base::Bind` checks if the receiver is evaluated to true and cancels the invocation
820if it's evaluated to false. You can specialize `base::IsWeakReceiver` to make
821an external smart pointer as a weak pointer.
tzik7c0c0cf12016-10-05 08:14:05822
Colin Blundellea615d422021-05-12 09:35:41823`base::UnwrapTraits<BoundObject>::Unwrap()` is called for each bound argument
824right before the callback calls the target function. You can specialize this to
825define an argument wrapper such as `base::Unretained`, `base::Owned`,
jdoerrie9d7236f62019-03-05 13:00:23826`base::RetainedRef` and `base::Passed`.
tzik7c0c0cf12016-10-05 08:14:05827
tzika4313512016-09-06 06:51:12828### How The Implementation Works:
tzik703f1562016-09-02 07:36:55829
830There are three main components to the system:
Colin Blundellea615d422021-05-12 09:35:41831 1) The `base::{Once, Repeating}Callback<>` classes.
832 2) The `base::BindOnce() and base::BindRepeating()` functions.
jdoerrie9d7236f62019-03-05 13:00:23833 3) The arguments wrappers (e.g., `base::Unretained()` and `base::Owned()`).
tzik703f1562016-09-02 07:36:55834
Brett Wilson508162c2017-09-27 22:24:46835The Callback classes represent a generic function pointer. Internally, it
836stores a refcounted piece of state that represents the target function and all
Colin Blundellea615d422021-05-12 09:35:41837its bound parameters. The `base::{Once, Repeating}Callback` constructor takes a
Brett Wilson508162c2017-09-27 22:24:46838`base::BindStateBase*`, which is upcasted from a `base::BindState<>`. In the
839context of the constructor, the static type of this `base::BindState<>` pointer
840uniquely identifies the function it is representing, all its bound parameters,
841and a `Run()` method that is capable of invoking the target.
tzik703f1562016-09-02 07:36:55842
Colin Blundellea615d422021-05-12 09:35:41843base::BindOnce() or base::BindRepeating() creates the `base::BindState<>` that
844has the full static type, and erases the target function type as well as the
845types of the bound parameters. It does this by storing a pointer to the specific
846`Run()` function, and upcasting the state of `base::BindState<>*` to a
847`base::BindStateBase*`. This is safe as long as this `BindStateBase` pointer is
848only used with the stored `Run()` pointer.
tzik703f1562016-09-02 07:36:55849
Colin Blundellea615d422021-05-12 09:35:41850These bind functions, along with a set of internal templates, are responsible
851for
tzik703f1562016-09-02 07:36:55852
853 - Unwrapping the function signature into return type, and parameters
854 - Determining the number of parameters that are bound
855 - Creating the BindState storing the bound parameters
856 - Performing compile-time asserts to avoid error-prone behavior
Armando Miragliacce1eb42018-08-16 14:35:44857 - Returning a `Callback<>` with an arity matching the number of unbound
tzik703f1562016-09-02 07:36:55858 parameters and that knows the correct refcounting semantics for the
859 target object if we are binding a method.
860
Brett Wilson508162c2017-09-27 22:24:46861The `base::Bind` functions do the above using type-inference and variadic
862templates.
tzik703f1562016-09-02 07:36:55863
Colin Blundellea615d422021-05-12 09:35:41864By default `base::Bind{Once, Repeating}()` will store copies of all bound parameters, and
Brett Wilson508162c2017-09-27 22:24:46865attempt to refcount a target object if the function being bound is a class
866method. These copies are created even if the function takes parameters as const
tzik703f1562016-09-02 07:36:55867references. (Binding to non-const references is forbidden, see bind.h.)
868
tzika4313512016-09-06 06:51:12869To change this behavior, we introduce a set of argument wrappers (e.g.,
jdoerrie9d7236f62019-03-05 13:00:23870`base::Unretained()`). These are simple container templates that are passed by
danakjdb9ae7942020-11-11 16:01:35871value, and wrap a pointer to argument. Each helper has a comment describing it
872in base/bind.h.
tzik703f1562016-09-02 07:36:55873
tzik7c0c0cf12016-10-05 08:14:05874These types are passed to the `Unwrap()` functions to modify the behavior of
Colin Blundellea615d422021-05-12 09:35:41875`base::Bind{Once, Repeating}()`. The `Unwrap()` functions change behavior by doing partial
tzik7c0c0cf12016-10-05 08:14:05876specialization based on whether or not a parameter is a wrapper type.
tzik703f1562016-09-02 07:36:55877
jdoerrie9d7236f62019-03-05 13:00:23878`base::Unretained()` is specific to Chromium.
tzik703f1562016-09-02 07:36:55879
tzika4313512016-09-06 06:51:12880### Missing Functionality
tzik703f1562016-09-02 07:36:55881 - Binding arrays to functions that take a non-const pointer.
882 Example:
883```cpp
884void Foo(const char* ptr);
885void Bar(char* ptr);
Colin Blundellea615d422021-05-12 09:35:41886base::BindOnce(&Foo, "test");
887base::BindOnce(&Bar, "test"); // This fails because ptr is not const.
tzik703f1562016-09-02 07:36:55888```
Gayane Petrosyan7f716982018-03-09 15:17:34889 - In case of partial binding of parameters a possibility of having unbound
890 parameters before bound parameters. Example:
891```cpp
892void Foo(int x, bool y);
Colin Blundellea615d422021-05-12 09:35:41893base::BindOnce(&Foo, _1, false); // _1 is a placeholder.
Gayane Petrosyan7f716982018-03-09 15:17:34894```
tzik703f1562016-09-02 07:36:55895
Colin Blundellea615d422021-05-12 09:35:41896If you are thinking of forward declaring `base::{Once, Repeating}Callback` in your own header
Brett Wilson508162c2017-09-27 22:24:46897file, please include "base/callback_forward.h" instead.