blob: 36e66c792ba08ff96d9801b5b0874502b1bbba0d [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
Avi Drissmand4459db2023-01-18 02:45:149base/functional/bind.h, they provide a type-safe method for performing partial
10application of 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
Arthur Milchiorcc277f02023-07-06 07:59:0320base::RepeatingCallback, as `base::RepeatingClosure`. Note that this is NOT the
Colin Blundellea615d422021-05-12 09:35:4121same 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 =
Sean Maher70f2942932023-01-04 22:15:06204 base::SequencedTaskRunner::GetCurrentDefault();
kylechardde7d232020-11-16 17:35:09205
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 =
Byron Lee71cf8b52023-08-16 09:10:33307 base::BarrierCallback<Data>(sources_.size(), base::BindOnce(&Merge));
Roland Bock6269edb2022-01-04 19:34:15308 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
Slobodan Pejic12e10322024-01-29 19:00:48386Binding a non-const method with a const object is not allowed, for example:
387
388```cpp
389class MyClass {
390 public:
391 base::OnceClosure GetCallback() const {
392 base::BindOnce(
393 // A template error will prevent the non-const method from being bound
394 // to the the WeakPtr<const MyClass>.
395 &MyClass::OnCallback,
396 weak_factory_.GetWeakPtr());
397 }
398
399 private:
400 void OnCallback(); // non-const
401 base::WeakPtrFactory<MyClass> weak_factory_{this};
402}
403```
404
tzika4313512016-09-06 06:51:12405### Running A Callback
tzik703f1562016-09-02 07:36:55406
tzik7c0c0cf12016-10-05 08:14:05407Callbacks can be run with their `Run` method, which has the same signature as
Brett Wilson508162c2017-09-27 22:24:46408the template argument to the callback. Note that `base::OnceCallback::Run`
409consumes the callback object and can only be invoked on a callback rvalue.
tzik703f1562016-09-02 07:36:55410
411```cpp
Colin Blundellea615d422021-05-12 09:35:41412void DoSomething(const base::RepeatingCallback<void(int, std::string)>& callback) {
tzik703f1562016-09-02 07:36:55413 callback.Run(5, "hello");
414}
tzik7c0c0cf12016-10-05 08:14:05415
Brett Wilson508162c2017-09-27 22:24:46416void DoSomethingOther(base::OnceCallback<void(int, std::string)> callback) {
tzik7c0c0cf12016-10-05 08:14:05417 std::move(callback).Run(5, "hello");
418}
tzik703f1562016-09-02 07:36:55419```
420
tzik7c0c0cf12016-10-05 08:14:05421RepeatingCallbacks can be run more than once (they don't get deleted or marked
Brett Wilson508162c2017-09-27 22:24:46422when run). However, this precludes using `base::Passed` (see below).
tzik703f1562016-09-02 07:36:55423
424```cpp
Brett Wilson508162c2017-09-27 22:24:46425void DoSomething(const base::RepeatingCallback<double(double)>& callback) {
tzik703f1562016-09-02 07:36:55426 double myresult = callback.Run(3.14159);
427 myresult += callback.Run(2.71828);
428}
429```
430
michaelpg0f156e12017-03-18 02:49:09431If running a callback could result in its own destruction (e.g., if the callback
432recipient deletes the object the callback is a member of), the callback should
Greg Thompsonddc84d42021-01-04 10:10:02433be moved or copied onto the stack before it can be safely invoked. (Note that
434this is only an issue for RepeatingCallbacks, because a OnceCallback always has
435to be moved for execution.)
michaelpg0f156e12017-03-18 02:49:09436
437```cpp
438void Foo::RunCallback() {
Bence Béky15327452018-05-10 20:59:07439 std::move(&foo_deleter_callback_).Run();
michaelpg0f156e12017-03-18 02:49:09440}
441```
442
Peter Kasting341e1fb2018-02-24 00:03:01443### Creating a Callback That Does Nothing
444
445Sometimes you need a callback that does nothing when run (e.g. test code that
446doesn't care to be notified about certain types of events). It may be tempting
447to pass a default-constructed callback of the right type:
448
449```cpp
450using MyCallback = base::OnceCallback<void(bool arg)>;
451void MyFunction(MyCallback callback) {
452 std::move(callback).Run(true); // Uh oh...
453}
454...
455MyFunction(MyCallback()); // ...this will crash when Run()!
456```
457
458Default-constructed callbacks are null, and thus cannot be Run(). Instead, use
459`base::DoNothing()`:
460
461```cpp
462...
463MyFunction(base::DoNothing()); // Can be Run(), will no-op
464```
465
466`base::DoNothing()` can be passed for any OnceCallback or RepeatingCallback that
467returns void.
468
469Implementation-wise, `base::DoNothing()` is actually a functor which produces a
470callback from `operator()`. This makes it unusable when trying to bind other
471arguments to it. Normally, the only reason to bind arguments to DoNothing() is
472to manage object lifetimes, and in these cases, you should strive to use idioms
473like DeleteSoon(), ReleaseSoon(), or RefCountedDeleteOnSequence instead. If you
474truly need to bind an argument to DoNothing(), or if you need to explicitly
475create a callback object (because implicit conversion through operator()() won't
476compile), you can instantiate directly:
477
478```cpp
479// Binds |foo_ptr| to a no-op OnceCallback takes a scoped_refptr<Foo>.
480// ANTIPATTERN WARNING: This should likely be changed to ReleaseSoon()!
Dmitrii Kuragin2e7da8652022-06-14 20:17:21481base::BindOnce(base::DoNothingAs<void(scoped_refptr<Foo>)>(), foo_ptr);
Peter Kasting341e1fb2018-02-24 00:03:01482```
483
tzika4313512016-09-06 06:51:12484### Passing Unbound Input Parameters
tzik703f1562016-09-02 07:36:55485
486Unbound parameters are specified at the time a callback is `Run()`. They are
Colin Blundellea615d422021-05-12 09:35:41487specified in the `base::{Once, Repeating}Callback` template type:
tzik703f1562016-09-02 07:36:55488
489```cpp
490void MyFunc(int i, const std::string& str) {}
Colin Blundellea615d422021-05-12 09:35:41491base::RepeatingCallback<void(int, const std::string&)> cb = base::BindRepeating(&MyFunc);
tzik703f1562016-09-02 07:36:55492cb.Run(23, "hello, world");
493```
494
tzika4313512016-09-06 06:51:12495### Passing Bound Input Parameters
tzik703f1562016-09-02 07:36:55496
tzika4313512016-09-06 06:51:12497Bound parameters are specified when you create the callback as arguments to
Colin Blundellea615d422021-05-12 09:35:41498`base::Bind{Once, Repeating}()`. They will be passed to the function and the `Run()`ner of the
Brett Wilson508162c2017-09-27 22:24:46499callback doesn't see those values or even know that the function it's calling.
tzik703f1562016-09-02 07:36:55500
501```cpp
502void MyFunc(int i, const std::string& str) {}
Colin Blundellea615d422021-05-12 09:35:41503base::RepeatingCallback<void()> cb = base::BindRepeating(&MyFunc, 23, "hello world");
tzik703f1562016-09-02 07:36:55504cb.Run();
505```
506
Colin Blundellea615d422021-05-12 09:35:41507As described earlier, a callback with no unbound input parameters
508(`base::RepeatingCallback<void()>`) is called a `base::RepeatingClosure`. So we
509could have also written:
tzik703f1562016-09-02 07:36:55510
511```cpp
Colin Blundellea615d422021-05-12 09:35:41512base::RepeatingClosure cb = base::BindRepeating(&MyFunc, 23, "hello world");
tzik703f1562016-09-02 07:36:55513```
514
515When calling member functions, bound parameters just go after the object
516pointer.
517
518```cpp
Colin Blundellea615d422021-05-12 09:35:41519base::RepeatingClosure cb = base::BindRepeating(&MyClass::MyFunc, this, 23, "hello world");
tzik703f1562016-09-02 07:36:55520```
521
Matt Giuca7e81b22e2019-12-12 02:41:21522### Partial Binding Of Parameters
tzik703f1562016-09-02 07:36:55523
tzika4313512016-09-06 06:51:12524You can specify some parameters when you create the callback, and specify the
525rest when you execute the callback.
tzik703f1562016-09-02 07:36:55526
tzik703f1562016-09-02 07:36:55527When calling a function bound parameters are first, followed by unbound
528parameters.
529
Gabriel Charette90480312018-02-16 15:10:05530```cpp
531void ReadIntFromFile(const std::string& filename,
532 base::OnceCallback<void(int)> on_read);
533
534void DisplayIntWithPrefix(const std::string& prefix, int result) {
535 LOG(INFO) << prefix << result;
536}
537
538void AnotherFunc(const std::string& file) {
539 ReadIntFromFile(file, base::BindOnce(&DisplayIntWithPrefix, "MyPrefix: "));
540};
541```
542
Matt Giuca7e81b22e2019-12-12 02:41:21543This technique is known as [partial
544application](http://en.wikipedia.org/wiki/Partial_application). It should be
545used in lieu of creating an adapter class that holds the bound arguments. Notice
546also that the `"MyPrefix: "` argument is actually a `const char*`, while
547`DisplayIntWithPrefix` actually wants a `const std::string&`. Like normal
548function dispatch, `base::Bind`, will coerce parameter types if possible.
Gabriel Charette90480312018-02-16 15:10:05549
Max Morinb51cf512018-02-19 12:49:49550### Avoiding Copies With Callback Parameters
tzik7c0c0cf12016-10-05 08:14:05551
Max Morinb51cf512018-02-19 12:49:49552A parameter of `base::BindRepeating()` or `base::BindOnce()` is moved into its
553internal storage if it is passed as a rvalue.
tzik7c0c0cf12016-10-05 08:14:05554
555```cpp
556std::vector<int> v = {1, 2, 3};
557// |v| is moved into the internal storage without copy.
Colin Blundellea615d422021-05-12 09:35:41558base::BindOnce(&Foo, std::move(v));
tzik7c0c0cf12016-10-05 08:14:05559```
560
561```cpp
tzik7c0c0cf12016-10-05 08:14:05562// The vector is moved into the internal storage without copy.
Colin Blundellea615d422021-05-12 09:35:41563base::BindOnce(&Foo, std::vector<int>({1, 2, 3}));
tzik7c0c0cf12016-10-05 08:14:05564```
565
Max Morinb51cf512018-02-19 12:49:49566Arguments bound with `base::BindOnce()` are always moved, if possible, to the
567target function.
568A function parameter that is passed by value and has a move constructor will be
569moved instead of copied.
570This makes it easy to use move-only types with `base::BindOnce()`.
571
572In contrast, arguments bound with `base::BindRepeating()` are only moved to the
573target function if the argument is bound with `base::Passed()`.
574
575**DANGER**:
576A `base::RepeatingCallback` can only be run once if arguments were bound with
577`base::Passed()`.
578For this reason, avoid `base::Passed()`.
579If you know a callback will only be called once, prefer to refactor code to
580work with `base::OnceCallback` instead.
581
582Avoid using `base::Passed()` with `base::BindOnce()`, as `std::move()` does the
583same thing and is more familiar.
tzik7c0c0cf12016-10-05 08:14:05584
585```cpp
586void Foo(std::unique_ptr<int>) {}
Max Morinb51cf512018-02-19 12:49:49587auto p = std::make_unique<int>(42);
tzik7c0c0cf12016-10-05 08:14:05588
Colin Blundellea615d422021-05-12 09:35:41589// |p| is moved into the internal storage of BindOnce(), and moved out to |Foo|.
Brett Wilson508162c2017-09-27 22:24:46590base::BindOnce(&Foo, std::move(p));
Max Morinb51cf512018-02-19 12:49:49591base::BindRepeating(&Foo, base::Passed(&p)); // Ok, but subtle.
592base::BindRepeating(&Foo, base::Passed(std::move(p))); // Ok, but subtle.
tzik7c0c0cf12016-10-05 08:14:05593```
594
tzika4313512016-09-06 06:51:12595## Quick reference for advanced binding
tzik703f1562016-09-02 07:36:55596
tzika4313512016-09-06 06:51:12597### Binding A Class Method With Weak Pointers
tzik703f1562016-09-02 07:36:55598
Daniel Chengaf16de52022-08-01 22:46:04599Callbacks to a class method may be bound using a weak pointer as the receiver.
600A callback bound using a weak pointer receiver will be automatically cancelled
601(calling `Run()` becomes a no-op) if the weak pointer is invalidated, e.g. its
602associated class instance is destroyed.
Wez33276262019-06-21 00:11:20603
Daniel Chengaf16de52022-08-01 22:46:04604The most common way to use this pattern is by embedding a `base::WeakPtrFactory`
605field, e.g.:
Wez33276262019-06-21 00:11:20606
607```cpp
608class MyClass {
Daniel Chengaf16de52022-08-01 22:46:04609 public:
610 MyClass();
611
612 void Foo();
613
614 private:
615 std::string data_;
616
617 // Chrome's compiler toolchain enforces that any `WeakPtrFactory`
618 // fields are declared last, to avoid destruction ordering issues.
Jeremy Roman0dd0b2f2019-07-16 21:00:43619 base::WeakPtrFactory<MyClass> weak_factory_{this};
Wez33276262019-06-21 00:11:20620};
621```
622
Daniel Chengaf16de52022-08-01 22:46:04623Then use `base::WeakPtrFactory<T>::GetWeakPtr()` as the receiver when
624binding a callback:
Wez33276262019-06-21 00:11:20625
Daniel Chengaf16de52022-08-01 22:46:04626```cpp
Sean Maher70f2942932023-01-04 22:15:06627base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
Daniel Chengaf16de52022-08-01 22:46:04628 FROM_HERE,
629 base::BindOnce(&MyClass::Foo, weak_factory_.GetWeakPtr());
630```
631
632If `this` is destroyed before the posted callback runs, the callback will
633simply become a no-op when run, rather than being a use-after-free bug on
634the destroyed `MyClass` instance.
635
636**Sequence safety**
637
638Class method callbacks bound to `base::WeakPtr`s must be run on the same
639sequence on which the object will be destroyed to avoid potential races
640between object destruction and callback execution. The same caveat applies if
641a class manually invalidates live `base::WeakPtr`s with
642`base::WeakPtrFactory<T>::InvalidateWeakPtrs()`.
tzik703f1562016-09-02 07:36:55643
tzika4313512016-09-06 06:51:12644### Binding A Class Method With Manual Lifetime Management
tzik703f1562016-09-02 07:36:55645
Daniel Chengaf16de52022-08-01 22:46:04646If a callback bound to a class method does not need cancel-on-destroy
647semantics (because there is some external guarantee that the class instance will
648always be live when running the callback), then use:
649
tzik703f1562016-09-02 07:36:55650```cpp
Daniel Chengaf16de52022-08-01 22:46:04651// base::Unretained() is safe since `this` joins `background_thread_` in the
652// destructor.
653background_thread_->PostTask(
654 FROM_HERE, base::BindOnce(&MyClass::Foo, base::Unretained(this)));
tzik703f1562016-09-02 07:36:55655```
656
Daniel Chengaf16de52022-08-01 22:46:04657It is often a good idea to add a brief comment to explain why
658`base::Unretained()` is safe in this context; if nothing else, for future code
659archaeologists trying to fix a use-after-free bug.
660
661An alternative is `base::WeakPtrFactory<T>::GetSafeRef()`:
662
663```cpp
664background_thread_->PostTask(
665 FROM_HERE, base::BindOnce(&MyClass::Foo, weak_factory_.GetSafeRef());
666```
667
668Similar to `base::Unretained()`, this disables cancel-on-destroy semantics;
669unlike `base::Unretained()`, this is guaranteed to terminate safely if the
670lifetime expectations are violated.
tzik703f1562016-09-02 07:36:55671
tzika4313512016-09-06 06:51:12672### Binding A Class Method And Having The Callback Own The Class
tzik703f1562016-09-02 07:36:55673
674```cpp
675MyClass* myclass = new MyClass;
Colin Blundellea615d422021-05-12 09:35:41676base::BindOnce(&MyClass::Foo, base::Owned(myclass));
tzik703f1562016-09-02 07:36:55677```
678
tzika4313512016-09-06 06:51:12679The object will be deleted when the callback is destroyed, even if it's not run
680(like if you post a task during shutdown). Potentially useful for "fire and
681forget" cases.
tzik703f1562016-09-02 07:36:55682
tzik7c0c0cf12016-10-05 08:14:05683Smart pointers (e.g. `std::unique_ptr<>`) are also supported as the receiver.
684
685```cpp
686std::unique_ptr<MyClass> myclass(new MyClass);
Colin Blundellea615d422021-05-12 09:35:41687base::BindOnce(&MyClass::Foo, std::move(myclass));
tzik7c0c0cf12016-10-05 08:14:05688```
689
tzika4313512016-09-06 06:51:12690### Ignoring Return Values
tzik703f1562016-09-02 07:36:55691
tzika4313512016-09-06 06:51:12692Sometimes you want to call a function that returns a value in a callback that
693doesn't expect a return value.
tzik703f1562016-09-02 07:36:55694
695```cpp
Wen Fandd472022021-03-12 01:31:09696int DoSomething(int arg) {
697 cout << arg << endl;
698 return arg;
699}
danakj9335cb1c2020-10-28 20:21:21700base::RepeatingCallback<void(int)> cb =
701 base::BindRepeating(IgnoreResult(&DoSomething));
702```
703
704Similarly, you may want to use an existing callback that returns a value in a
705place that expects a void return type.
706
707```cpp
708base::RepeatingCallback<int()> cb = base::BindRepeating([](){ return 5; });
709base::RepeatingClosure void_cb = base::BindRepeating(base::IgnoreResult(cb));
tzik703f1562016-09-02 07:36:55710```
711
Nicolas Dossou-Gbete51290c2f2022-10-19 12:50:34712### Ignoring Arguments Values
713
Evan Stade5df74692023-10-02 23:15:57714Sometimes you want to use a function that takes fewer arguments than the
715designated callback type expects. The extra arguments can be ignored as long
716as they are leading.
Nicolas Dossou-Gbete51290c2f2022-10-19 12:50:34717
718```cpp
Keren Zhu9cd105c82024-08-03 00:00:12719bool LogError(char* error_message) {
720 if (error_message) {
Evan Stade5df74692023-10-02 23:15:57721 cout << "Log: " << error_message << endl;
Keren Zhu9cd105c82024-08-03 00:00:12722 return false;
723 }
724 return true;
Nicolas Dossou-Gbete51290c2f2022-10-19 12:50:34725}
Keren Zhu9cd105c82024-08-03 00:00:12726base::RepeatingCallback<bool(int, char*)> cb =
Evan Stade5df74692023-10-02 23:15:57727 base::IgnoreArgs<int>(base::BindRepeating(&LogError));
Keren Zhu9cd105c82024-08-03 00:00:12728CHECK_EQ(true, cb.Run(42, nullptr));
Nicolas Dossou-Gbete51290c2f2022-10-19 12:50:34729```
730
Evan Stade5df74692023-10-02 23:15:57731Note in the example above that the type(s) passed to `IgnoreArgs` represent
732the additional prepended parameters (those which will be "ignored"). The other
733arguments to `cb` are inferred from the callback that is being wrapped.
734
735`IgnoreArgs` can be used to adapt a closure to a callback, ignoring all the
736arguments that are eventually passed:
Nicolas Dossou-Gbete51290c2f2022-10-19 12:50:34737
738```cpp
739base::OnceClosure closure = base::BindOnce([](){ cout << "Hello!" << endl; });
740base::OnceCallback<void(int)> int_cb =
741 base::IgnoreArgs<int>(std::move(closure));
742```
743
Colin Blundellea615d422021-05-12 09:35:41744## Quick reference for binding parameters to BindOnce() and BindRepeating()
tzik703f1562016-09-02 07:36:55745
Colin Blundellea615d422021-05-12 09:35:41746Bound parameters are specified as arguments to `base::Bind{Once, Repeating}()`
747and are passed to the functions.
tzik703f1562016-09-02 07:36:55748
tzika4313512016-09-06 06:51:12749### Passing Parameters Owned By The Callback
tzik703f1562016-09-02 07:36:55750
751```cpp
752void Foo(int* arg) { cout << *arg << endl; }
753int* pn = new int(1);
Colin Blundellea615d422021-05-12 09:35:41754base::RepeatingClosure foo_callback = base::BindRepeating(&foo, base::Owned(pn));
tzik703f1562016-09-02 07:36:55755```
756
tzika4313512016-09-06 06:51:12757The parameter will be deleted when the callback is destroyed, even if it's not
758run (like if you post a task during shutdown).
tzik703f1562016-09-02 07:36:55759
tzika4313512016-09-06 06:51:12760### Passing Parameters As A unique_ptr
tzik703f1562016-09-02 07:36:55761
762```cpp
763void TakesOwnership(std::unique_ptr<Foo> arg) {}
Max Morinb51cf512018-02-19 12:49:49764auto f = std::make_unique<Foo>();
tzik703f1562016-09-02 07:36:55765// f becomes null during the following call.
Max Morinb51cf512018-02-19 12:49:49766base::OnceClosure cb = base::BindOnce(&TakesOwnership, std::move(f));
tzik703f1562016-09-02 07:36:55767```
768
tzika4313512016-09-06 06:51:12769Ownership of the parameter will be with the callback until the callback is run,
770and then ownership is passed to the callback function. This means the callback
771can only be run once. If the callback is never run, it will delete the object
772when it's destroyed.
tzik703f1562016-09-02 07:36:55773
tzika4313512016-09-06 06:51:12774### Passing Parameters As A scoped_refptr
tzik703f1562016-09-02 07:36:55775
776```cpp
777void TakesOneRef(scoped_refptr<Foo> arg) {}
tzik7c0c0cf12016-10-05 08:14:05778scoped_refptr<Foo> f(new Foo);
Colin Blundellea615d422021-05-12 09:35:41779base::RepeatingClosure cb = base::BindRepeating(&TakesOneRef, f);
tzik703f1562016-09-02 07:36:55780```
781
tzika4313512016-09-06 06:51:12782This should "just work." The closure will take a reference as long as it is
783alive, and another reference will be taken for the called function.
tzik703f1562016-09-02 07:36:55784
tzik7c0c0cf12016-10-05 08:14:05785```cpp
786void DontTakeRef(Foo* arg) {}
787scoped_refptr<Foo> f(new Foo);
Colin Blundellea615d422021-05-12 09:35:41788base::RepeatingClosure cb = base::BindRepeating(&DontTakeRef, base::RetainedRef(f));
tzik7c0c0cf12016-10-05 08:14:05789```
790
Brett Wilson508162c2017-09-27 22:24:46791`base::RetainedRef` holds a reference to the object and passes a raw pointer to
tzik7c0c0cf12016-10-05 08:14:05792the object when the Callback is run.
793
kylechar72e6f782021-03-17 17:43:38794### Binding Const Reference Parameters
tzik703f1562016-09-02 07:36:55795
kylechar72e6f782021-03-17 17:43:38796If the callback function takes a const reference parameter then the value is
797*copied* when bound unless `std::ref` or `std::cref` is used. Example:
tzik703f1562016-09-02 07:36:55798
799```cpp
800void foo(const int& arg) { printf("%d %p\n", arg, &arg); }
801int n = 1;
kylechar72e6f782021-03-17 17:43:38802base::OnceClosure has_copy = base::BindOnce(&foo, n);
803base::OnceClosure has_ref = base::BindOnce(&foo, std::cref(n));
tzik703f1562016-09-02 07:36:55804n = 2;
kylechar72e6f782021-03-17 17:43:38805foo(n); // Prints "2 0xaaaaaaaaaaaa"
806std::move(has_copy).Run(); // Prints "1 0xbbbbbbbbbbbb"
807std::move(has_ref).Run(); // Prints "2 0xaaaaaaaaaaaa"
tzik703f1562016-09-02 07:36:55808```
809
kylechar72e6f782021-03-17 17:43:38810Normally parameters are copied in the closure. **DANGER**: `std::ref` and
811`std::cref` store a (const) reference instead, referencing the original
812parameter. This means that you must ensure the object outlives the callback!
813
814### Binding Non-Const Reference Parameters
815
816If the callback function takes a non-const reference then the bind statement
817must specify what behavior is desired. If a reference that can mutate the
818original value is desired then `std::ref` is used. If the callback should take
819ownership of the value, either by making a copy or moving an existing value,
820then `base::OwnedRef` is used. If neither is used the bind statement will fail
821to compile. Example:
822
823```cpp
824void foo(int& arg) {
825 printf("%d\n", arg);
826 ++arg;
827}
828
829int n = 0;
830base::RepeatingClosure has_ref = base::BindRepeating(&foo, std::ref(n));
831base::RepeatingClosure has_copy = base::BindRepeating(&foo, base::OwnedRef(n));
832
833foo(n); // Prints "0"
834has_ref.Run(); // Prints "1"
835has_ref.Run(); // Prints "2"
836foo(n); // Prints "3"
837
838has_copy.Run(); // Prints "0"
839has_copy.Run(); // Prints "1"
840
841// This will fail to compile.
842base::RepeatingClosure cb = base::BindRepeating(&foo, n);
843```
844
845Normally parameters are copied in the closure. **DANGER**: `std::ref` stores a
846reference instead, referencing the original parameter. This means that you must
847ensure the object outlives the callback!
848
849If the callback function has an output reference parameter but the output value
850isn't needed then `base::OwnedRef()` is a convenient way to handle it. The
851callback owned value will be mutated by the callback function and then deleted
852along with the callback. Example:
853
854```cpp
855bool Compute(size_t index, int& output);
856
857// The `output` parameter isn't important for the callback, it only cares about
858// the return value.
859base::OnceClosure cb = base::BindOnce(&Compute, index, base::OwnedRef(0));
860bool success = std::move(cb).Run();
861```
tzik703f1562016-09-02 07:36:55862
tzika4313512016-09-06 06:51:12863## Implementation notes
tzik703f1562016-09-02 07:36:55864
tzika4313512016-09-06 06:51:12865### Where Is This Design From:
tzik703f1562016-09-02 07:36:55866
Colin Blundellea615d422021-05-12 09:35:41867The design is heavily influenced by C++'s `tr1::function` / `tr1::bind`, and by
868the "Google Callback" system used inside Google.
tzik703f1562016-09-02 07:36:55869
tzik7c0c0cf12016-10-05 08:14:05870### Customizing the behavior
871
Brett Wilson508162c2017-09-27 22:24:46872There are several injection points that controls binding behavior from outside
873of its implementation.
tzik7c0c0cf12016-10-05 08:14:05874
875```cpp
Brett Wilson508162c2017-09-27 22:24:46876namespace base {
877
tzik7c0c0cf12016-10-05 08:14:05878template <typename Receiver>
Peter Kastingd077bb22023-12-16 08:40:00879struct IsWeakReceiver : std::false_type {};
tzik7c0c0cf12016-10-05 08:14:05880
881template <typename Obj>
John Admanski5c308c52023-11-30 18:13:50882struct BindUnwrapTraits {
tzik7c0c0cf12016-10-05 08:14:05883 template <typename T>
884 T&& Unwrap(T&& obj) {
885 return std::forward<T>(obj);
886 }
887};
Brett Wilson508162c2017-09-27 22:24:46888
889} // namespace base
tzik7c0c0cf12016-10-05 08:14:05890```
891
Brett Wilson508162c2017-09-27 22:24:46892If `base::IsWeakReceiver<Receiver>::value` is true on a receiver of a method,
893`base::Bind` checks if the receiver is evaluated to true and cancels the invocation
894if it's evaluated to false. You can specialize `base::IsWeakReceiver` to make
895an external smart pointer as a weak pointer.
tzik7c0c0cf12016-10-05 08:14:05896
John Admanski5c308c52023-11-30 18:13:50897`base::BindUnwrapTraits<BoundObject>::Unwrap()` is called for each bound argument
Colin Blundellea615d422021-05-12 09:35:41898right before the callback calls the target function. You can specialize this to
899define an argument wrapper such as `base::Unretained`, `base::Owned`,
jdoerrie9d7236f62019-03-05 13:00:23900`base::RetainedRef` and `base::Passed`.
tzik7c0c0cf12016-10-05 08:14:05901
tzika4313512016-09-06 06:51:12902### How The Implementation Works:
tzik703f1562016-09-02 07:36:55903
904There are three main components to the system:
Colin Blundellea615d422021-05-12 09:35:41905 1) The `base::{Once, Repeating}Callback<>` classes.
906 2) The `base::BindOnce() and base::BindRepeating()` functions.
jdoerrie9d7236f62019-03-05 13:00:23907 3) The arguments wrappers (e.g., `base::Unretained()` and `base::Owned()`).
tzik703f1562016-09-02 07:36:55908
Brett Wilson508162c2017-09-27 22:24:46909The Callback classes represent a generic function pointer. Internally, it
910stores a refcounted piece of state that represents the target function and all
Colin Blundellea615d422021-05-12 09:35:41911its bound parameters. The `base::{Once, Repeating}Callback` constructor takes a
Brett Wilson508162c2017-09-27 22:24:46912`base::BindStateBase*`, which is upcasted from a `base::BindState<>`. In the
913context of the constructor, the static type of this `base::BindState<>` pointer
914uniquely identifies the function it is representing, all its bound parameters,
915and a `Run()` method that is capable of invoking the target.
tzik703f1562016-09-02 07:36:55916
Colin Blundellea615d422021-05-12 09:35:41917base::BindOnce() or base::BindRepeating() creates the `base::BindState<>` that
918has the full static type, and erases the target function type as well as the
919types of the bound parameters. It does this by storing a pointer to the specific
920`Run()` function, and upcasting the state of `base::BindState<>*` to a
921`base::BindStateBase*`. This is safe as long as this `BindStateBase` pointer is
922only used with the stored `Run()` pointer.
tzik703f1562016-09-02 07:36:55923
Colin Blundellea615d422021-05-12 09:35:41924These bind functions, along with a set of internal templates, are responsible
925for
tzik703f1562016-09-02 07:36:55926
927 - Unwrapping the function signature into return type, and parameters
928 - Determining the number of parameters that are bound
929 - Creating the BindState storing the bound parameters
930 - Performing compile-time asserts to avoid error-prone behavior
Armando Miragliacce1eb42018-08-16 14:35:44931 - Returning a `Callback<>` with an arity matching the number of unbound
tzik703f1562016-09-02 07:36:55932 parameters and that knows the correct refcounting semantics for the
933 target object if we are binding a method.
934
Brett Wilson508162c2017-09-27 22:24:46935The `base::Bind` functions do the above using type-inference and variadic
936templates.
tzik703f1562016-09-02 07:36:55937
Colin Blundellea615d422021-05-12 09:35:41938By default `base::Bind{Once, Repeating}()` will store copies of all bound parameters, and
Brett Wilson508162c2017-09-27 22:24:46939attempt to refcount a target object if the function being bound is a class
940method. These copies are created even if the function takes parameters as const
tzik703f1562016-09-02 07:36:55941references. (Binding to non-const references is forbidden, see bind.h.)
942
tzika4313512016-09-06 06:51:12943To change this behavior, we introduce a set of argument wrappers (e.g.,
jdoerrie9d7236f62019-03-05 13:00:23944`base::Unretained()`). These are simple container templates that are passed by
danakjdb9ae7942020-11-11 16:01:35945value, and wrap a pointer to argument. Each helper has a comment describing it
Avi Drissmand4459db2023-01-18 02:45:14946in base/functional/bind.h.
tzik703f1562016-09-02 07:36:55947
tzik7c0c0cf12016-10-05 08:14:05948These types are passed to the `Unwrap()` functions to modify the behavior of
Colin Blundellea615d422021-05-12 09:35:41949`base::Bind{Once, Repeating}()`. The `Unwrap()` functions change behavior by doing partial
tzik7c0c0cf12016-10-05 08:14:05950specialization based on whether or not a parameter is a wrapper type.
tzik703f1562016-09-02 07:36:55951
jdoerrie9d7236f62019-03-05 13:00:23952`base::Unretained()` is specific to Chromium.
tzik703f1562016-09-02 07:36:55953
tzika4313512016-09-06 06:51:12954### Missing Functionality
tzik703f1562016-09-02 07:36:55955 - Binding arrays to functions that take a non-const pointer.
956 Example:
957```cpp
958void Foo(const char* ptr);
959void Bar(char* ptr);
Colin Blundellea615d422021-05-12 09:35:41960base::BindOnce(&Foo, "test");
961base::BindOnce(&Bar, "test"); // This fails because ptr is not const.
tzik703f1562016-09-02 07:36:55962```
Gayane Petrosyan7f716982018-03-09 15:17:34963 - In case of partial binding of parameters a possibility of having unbound
964 parameters before bound parameters. Example:
965```cpp
966void Foo(int x, bool y);
Colin Blundellea615d422021-05-12 09:35:41967base::BindOnce(&Foo, _1, false); // _1 is a placeholder.
Gayane Petrosyan7f716982018-03-09 15:17:34968```
tzik703f1562016-09-02 07:36:55969
Avi Drissmand4459db2023-01-18 02:45:14970If you are thinking of forward declaring `base::{Once, Repeating}Callback` in
971your own header file, please include "base/functional/callback_forward.h"
972instead.