blob: 74252397b82422dc0feec2c5583daf85c87932b1 [file] [log] [blame] [view]
tzik7c0c0cf12016-10-05 08:14:051# Callback<> and Bind()
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
Brett Wilson508162c2017-09-27 22:24:467The templated `base::Callback<>` class is a generalized function object.
8Together with the `base::Bind()` function in base/bind.h, they provide a
9type-safe method for performing partial application of functions.
tzik703f1562016-09-02 07:36:5510
Matt Giuca7e81b22e2019-12-12 02:41:2111Partial application is the process of binding a subset of a function's arguments
12to produce another function that takes fewer arguments. This can be used to pass
13around a unit of delayed execution, much like lexical closures are used in other
14languages. For example, it is used in Chromium code to schedule tasks on
15different MessageLoops.
tzik703f1562016-09-02 07:36:5516
Brett Wilson508162c2017-09-27 22:24:4617A callback with no unbound input parameters (`base::Callback<void()>`) is
18called a `base::Closure`. Note that this is NOT the same as what other
19languages refer to as a closure -- it does not retain a reference to its
20enclosing environment.
tzik703f1562016-09-02 07:36:5521
tzik7c0c0cf12016-10-05 08:14:0522### OnceCallback<> And RepeatingCallback<>
23
Brett Wilson508162c2017-09-27 22:24:4624`base::OnceCallback<>` and `base::RepeatingCallback<>` are next gen callback
25classes, which are under development.
tzik7c0c0cf12016-10-05 08:14:0526
Brett Wilson508162c2017-09-27 22:24:4627`base::OnceCallback<>` is created by `base::BindOnce()`. This is a callback
28variant that is a move-only type and can be run only once. This moves out bound
29parameters from its internal storage to the bound function by default, so it's
30easier to use with movable types. This should be the preferred callback type:
31since the lifetime of the callback is clear, it's simpler to reason about when
32a callback that is passed between threads is destroyed.
tzik7c0c0cf12016-10-05 08:14:0533
Brett Wilson508162c2017-09-27 22:24:4634`base::RepeatingCallback<>` is created by `base::BindRepeating()`. This is a
35callback variant that is copyable that can be run multiple times. It uses
36internal ref-counting to make copies cheap. However, since ownership is shared,
37it is harder to reason about when the callback and the bound state are
38destroyed, especially when the callback is passed between threads.
tzik7c0c0cf12016-10-05 08:14:0539
Brett Wilson508162c2017-09-27 22:24:4640The legacy `base::Callback<>` is currently aliased to
41`base::RepeatingCallback<>`. In new code, prefer `base::OnceCallback<>` where
42possible, and use `base::RepeatingCallback<>` otherwise. Once the migration is
43complete, the type alias will be removed and `base::OnceCallback<>` will be renamed
44to `base::Callback<>` to emphasize that it should be preferred.
tzik7c0c0cf12016-10-05 08:14:0545
Brett Wilson508162c2017-09-27 22:24:4646`base::RepeatingCallback<>` is convertible to `base::OnceCallback<>` by the
47implicit conversion.
tzik7c0c0cf12016-10-05 08:14:0548
tzika4313512016-09-06 06:51:1249### Memory Management And Passing
tzik703f1562016-09-02 07:36:5550
danakje26d7cf2019-05-29 20:04:1451Pass `base::{Once,Repeating}Callback` objects by value if ownership is
52transferred; otherwise, pass it by const-reference.
tzik703f1562016-09-02 07:36:5553
tzik7c0c0cf12016-10-05 08:14:0554```cpp
55// |Foo| just refers to |cb| but doesn't store it nor consume it.
Brett Wilson508162c2017-09-27 22:24:4656bool Foo(const base::OnceCallback<void(int)>& cb) {
tzik7c0c0cf12016-10-05 08:14:0557 return cb.is_null();
58}
59
60// |Bar| takes the ownership of |cb| and stores |cb| into |g_cb|.
danakje26d7cf2019-05-29 20:04:1461base::RepeatingCallback<void(int)> g_cb;
62void Bar(base::RepeatingCallback<void(int)> cb) {
tzik7c0c0cf12016-10-05 08:14:0563 g_cb = std::move(cb);
64}
65
66// |Baz| takes the ownership of |cb| and consumes |cb| by Run().
Brett Wilson508162c2017-09-27 22:24:4667void Baz(base::OnceCallback<void(int)> cb) {
tzik7c0c0cf12016-10-05 08:14:0568 std::move(cb).Run(42);
69}
70
71// |Qux| takes the ownership of |cb| and transfers ownership to PostTask(),
72// which also takes the ownership of |cb|.
danakje26d7cf2019-05-29 20:04:1473void Qux(base::RepeatingCallback<void(int)> cb) {
74 PostTask(FROM_HERE, base::BindOnce(cb, 42));
75 PostTask(FROM_HERE, base::BindOnce(std::move(cb), 43));
tzik7c0c0cf12016-10-05 08:14:0576}
77```
78
danakje26d7cf2019-05-29 20:04:1479When you pass a `base::{Once,Repeating}Callback` object to a function parameter,
80use `std::move()` if you don't need to keep a reference to it, otherwise, pass the
Brett Wilson508162c2017-09-27 22:24:4681object directly. You may see a compile error when the function requires the
82exclusive ownership, and you didn't pass the callback by move. Note that the
danakje26d7cf2019-05-29 20:04:1483moved-from `base::{Once,Repeating}Callback` becomes null, as if its `Reset()`
84method had been called. Afterward, its `is_null()` method will return true and
85its `operator bool()` will return false.
tzik703f1562016-09-02 07:36:5586
danakjfcc5e7c2020-10-23 17:43:2787### Chaining callbacks
88
89When you have 2 callbacks that you wish to run in sequence, they can be joined
90together into a single callback through the use of `Then()`.
91
92Calling `Then()` on a `base::OnceCallback` joins a second callback that will be
93run together with, but after, the first callback. The return value from the
94first callback is passed along to the second, and the return value from the
95second callback is returned at the end. More concretely, calling `a.Then(b)`
96produces a new `base::OnceCallback` that will run `b(a());`, returning the
97result from `b`.
98
99This example uses `Then()` to join 2 `base::OnceCallback`s together:
100```cpp
101int Floor(float f) { return std::floor(f); }
102std::string IntToString(int i) { return base::NumberToString(i); }
103
104base::OnceCallback<int(float)> first = base::BindOnce(&Floor);
105base::OnceCallback<std::string(int)> second = base::BindOnce(&IntToString);
106
107// This will run |first|, run and pass the result to |second|, then return
108// the result from |second|.
109std::string r = std::move(first).Then(std::move(second)).Run(3.5f);
110// |r| will be "3". |first| and |second| are now both null, as they were
111// consumed to perform the join operation.
112```
113
114Similarly, `Then()` also works with `base::RepeatingCallback`; however, the
115joined callback must also be a `base::RepeatingCallback` to ensure the resulting
116callback can be invoked multiple times.
117
118This example uses `Then()` to join 2 `base::RepeatingCallback`s together:
119```cpp
120int Floor(float f) { return std::floor(f); }
121std::string IntToString(int i) { return base::NumberToString(i); }
122
123base::RepeatingCallback<int(float)> first = base::BindRepeating(&Floor);
124base::RepeatingCallback<std::string(int)> second = base::BindRepeating(&IntToString);
125
126// This creates a RepeatingCallback that will run |first|, run and pass the
127// result to |second|, then return the result from |second|.
128base::RepeatingCallback<std::string(float)> joined =
129 std::move(first).Then(std::move(second));
130// |first| and |second| are now both null, as they were consumed to perform
131// the join operation.
132
133// This runs the functor that was originally bound to |first|, then |second|.
134std::string r = joined.Run(3.5);
135// |r| will be "3".
136
137// It's valid to call it multiple times since all callbacks involved are
138// base::RepeatingCallbacks.
139r = joined.Run(2.5);
140// |r| is set to "2".
141```
142
143In the above example, casting the `base::RepeatingCallback` to an r-value with
144`std::move()` causes `Then()` to destroy the original callback, in the same way
145that occurs for joining `base::OnceCallback`s. However since a
146`base::RepeatingCallback` can be run multiple times, it can be joined
147non-destructively as well.
148```cpp
149int Floor(float f) { return std::floor(f); }
150std::string IntToString(int i) { return base::NumberToString(i); }
151
152base::RepeatingCallback<int(float)> first = base::BindRepeating(&Floor);
153base::RepeatingCallback<std::string(int)> second = base::BindRepeating(&IntToString);
154
155// This creates a RepeatingCallback that will run |first|, run and pass the
156// result to |second|, then return the result from |second|.
157std::string r = first.Then(second).Run(3.5f);
158// |r| will be 3, and |first| and |second| are still valid to use.
159
160// Runs Floor().
161int i = first.Run(5.5);
162// Runs IntToString().
163std::string s = second.Run(9);
164```
165
tzika4313512016-09-06 06:51:12166## Quick reference for basic stuff
tzik703f1562016-09-02 07:36:55167
tzika4313512016-09-06 06:51:12168### Binding A Bare Function
tzik703f1562016-09-02 07:36:55169
170```cpp
171int Return5() { return 5; }
Brett Wilson508162c2017-09-27 22:24:46172base::OnceCallback<int()> func_cb = base::BindOnce(&Return5);
tzik7c0c0cf12016-10-05 08:14:05173LOG(INFO) << std::move(func_cb).Run(); // Prints 5.
174```
175
176```cpp
177int Return5() { return 5; }
Brett Wilson508162c2017-09-27 22:24:46178base::RepeatingCallback<int()> func_cb = base::BindRepeating(&Return5);
tzik703f1562016-09-02 07:36:55179LOG(INFO) << func_cb.Run(); // Prints 5.
180```
181
tzik7c0c0cf12016-10-05 08:14:05182### Binding A Captureless Lambda
183
184```cpp
Brett Wilson508162c2017-09-27 22:24:46185base::Callback<int()> lambda_cb = base::Bind([] { return 4; });
tzik7c0c0cf12016-10-05 08:14:05186LOG(INFO) << lambda_cb.Run(); // Print 4.
187
Brett Wilson508162c2017-09-27 22:24:46188base::OnceCallback<int()> lambda_cb2 = base::BindOnce([] { return 3; });
tzik7c0c0cf12016-10-05 08:14:05189LOG(INFO) << std::move(lambda_cb2).Run(); // Print 3.
Erik Chen9425c0f2020-09-11 21:41:09190
191base::OnceCallback<int()> lambda_cb3 = base::BindOnce([] { return 2; });
192base::OnceCallback<int(base::OnceCallback<int()>)> lambda_cb4 =
193 base::BindOnce(
194 [](base::OnceCallback<int()> callback) {
195 return std::move(callback).Run(); },
196 std::move(lambda_cb3));
197LOG(INFO) << std::move(lambda_cb4).Run(); // Print 2.
198
tzik7c0c0cf12016-10-05 08:14:05199```
200
Raphael Kubo da Costa17c1618c2019-03-28 19:30:44201### Binding A Capturing Lambda (In Tests)
202
203When writing tests, it is often useful to capture arguments that need to be
204modified in a callback.
205
206``` cpp
207#include "base/test/bind_test_util.h"
208
209int i = 2;
210base::Callback<void()> lambda_cb = base::BindLambdaForTesting([&]() { i++; });
211lambda_cb.Run();
212LOG(INFO) << i; // Print 3;
213```
214
tzika4313512016-09-06 06:51:12215### Binding A Class Method
tzik703f1562016-09-02 07:36:55216
tzika4313512016-09-06 06:51:12217The first argument to bind is the member function to call, the second is the
218object on which to call it.
tzik703f1562016-09-02 07:36:55219
220```cpp
Brett Wilson508162c2017-09-27 22:24:46221class Ref : public base::RefCountedThreadSafe<Ref> {
tzik703f1562016-09-02 07:36:55222 public:
223 int Foo() { return 3; }
tzik703f1562016-09-02 07:36:55224};
225scoped_refptr<Ref> ref = new Ref();
Brett Wilson508162c2017-09-27 22:24:46226base::Callback<void()> ref_cb = base::Bind(&Ref::Foo, ref);
tzik703f1562016-09-02 07:36:55227LOG(INFO) << ref_cb.Run(); // Prints out 3.
228```
229
230By default the object must support RefCounted or you will get a compiler
tzik7c0c0cf12016-10-05 08:14:05231error. If you're passing between threads, be sure it's RefCountedThreadSafe! See
232"Advanced binding of member functions" below if you don't want to use reference
233counting.
tzik703f1562016-09-02 07:36:55234
tzika4313512016-09-06 06:51:12235### Running A Callback
tzik703f1562016-09-02 07:36:55236
tzik7c0c0cf12016-10-05 08:14:05237Callbacks can be run with their `Run` method, which has the same signature as
Brett Wilson508162c2017-09-27 22:24:46238the template argument to the callback. Note that `base::OnceCallback::Run`
239consumes the callback object and can only be invoked on a callback rvalue.
tzik703f1562016-09-02 07:36:55240
241```cpp
Brett Wilson508162c2017-09-27 22:24:46242void DoSomething(const base::Callback<void(int, std::string)>& callback) {
tzik703f1562016-09-02 07:36:55243 callback.Run(5, "hello");
244}
tzik7c0c0cf12016-10-05 08:14:05245
Brett Wilson508162c2017-09-27 22:24:46246void DoSomethingOther(base::OnceCallback<void(int, std::string)> callback) {
tzik7c0c0cf12016-10-05 08:14:05247 std::move(callback).Run(5, "hello");
248}
tzik703f1562016-09-02 07:36:55249```
250
tzik7c0c0cf12016-10-05 08:14:05251RepeatingCallbacks can be run more than once (they don't get deleted or marked
Brett Wilson508162c2017-09-27 22:24:46252when run). However, this precludes using `base::Passed` (see below).
tzik703f1562016-09-02 07:36:55253
254```cpp
Brett Wilson508162c2017-09-27 22:24:46255void DoSomething(const base::RepeatingCallback<double(double)>& callback) {
tzik703f1562016-09-02 07:36:55256 double myresult = callback.Run(3.14159);
257 myresult += callback.Run(2.71828);
258}
259```
260
michaelpg0f156e12017-03-18 02:49:09261If running a callback could result in its own destruction (e.g., if the callback
262recipient deletes the object the callback is a member of), the callback should
Bence Béky15327452018-05-10 20:59:07263be moved before it can be safely invoked. (Note that this is only an issue for
264RepeatingCallbacks, because a OnceCallback always has to be moved for
265execution.)
michaelpg0f156e12017-03-18 02:49:09266
267```cpp
268void Foo::RunCallback() {
Bence Béky15327452018-05-10 20:59:07269 std::move(&foo_deleter_callback_).Run();
michaelpg0f156e12017-03-18 02:49:09270}
271```
272
Peter Kasting341e1fb2018-02-24 00:03:01273### Creating a Callback That Does Nothing
274
275Sometimes you need a callback that does nothing when run (e.g. test code that
276doesn't care to be notified about certain types of events). It may be tempting
277to pass a default-constructed callback of the right type:
278
279```cpp
280using MyCallback = base::OnceCallback<void(bool arg)>;
281void MyFunction(MyCallback callback) {
282 std::move(callback).Run(true); // Uh oh...
283}
284...
285MyFunction(MyCallback()); // ...this will crash when Run()!
286```
287
288Default-constructed callbacks are null, and thus cannot be Run(). Instead, use
289`base::DoNothing()`:
290
291```cpp
292...
293MyFunction(base::DoNothing()); // Can be Run(), will no-op
294```
295
296`base::DoNothing()` can be passed for any OnceCallback or RepeatingCallback that
297returns void.
298
299Implementation-wise, `base::DoNothing()` is actually a functor which produces a
300callback from `operator()`. This makes it unusable when trying to bind other
301arguments to it. Normally, the only reason to bind arguments to DoNothing() is
302to manage object lifetimes, and in these cases, you should strive to use idioms
303like DeleteSoon(), ReleaseSoon(), or RefCountedDeleteOnSequence instead. If you
304truly need to bind an argument to DoNothing(), or if you need to explicitly
305create a callback object (because implicit conversion through operator()() won't
306compile), you can instantiate directly:
307
308```cpp
309// Binds |foo_ptr| to a no-op OnceCallback takes a scoped_refptr<Foo>.
310// ANTIPATTERN WARNING: This should likely be changed to ReleaseSoon()!
311base::Bind(base::DoNothing::Once<scoped_refptr<Foo>>(), foo_ptr);
312```
313
tzika4313512016-09-06 06:51:12314### Passing Unbound Input Parameters
tzik703f1562016-09-02 07:36:55315
316Unbound parameters are specified at the time a callback is `Run()`. They are
Brett Wilson508162c2017-09-27 22:24:46317specified in the `base::Callback` template type:
tzik703f1562016-09-02 07:36:55318
319```cpp
320void MyFunc(int i, const std::string& str) {}
Brett Wilson508162c2017-09-27 22:24:46321base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc);
tzik703f1562016-09-02 07:36:55322cb.Run(23, "hello, world");
323```
324
tzika4313512016-09-06 06:51:12325### Passing Bound Input Parameters
tzik703f1562016-09-02 07:36:55326
tzika4313512016-09-06 06:51:12327Bound parameters are specified when you create the callback as arguments to
Brett Wilson508162c2017-09-27 22:24:46328`base::Bind()`. They will be passed to the function and the `Run()`ner of the
329callback doesn't see those values or even know that the function it's calling.
tzik703f1562016-09-02 07:36:55330
331```cpp
332void MyFunc(int i, const std::string& str) {}
Brett Wilson508162c2017-09-27 22:24:46333base::Callback<void()> cb = base::Bind(&MyFunc, 23, "hello world");
tzik703f1562016-09-02 07:36:55334cb.Run();
335```
336
Brett Wilson508162c2017-09-27 22:24:46337A callback with no unbound input parameters (`base::Callback<void()>`) is
338called a `base::Closure`. So we could have also written:
tzik703f1562016-09-02 07:36:55339
340```cpp
Brett Wilson508162c2017-09-27 22:24:46341base::Closure cb = base::Bind(&MyFunc, 23, "hello world");
tzik703f1562016-09-02 07:36:55342```
343
344When calling member functions, bound parameters just go after the object
345pointer.
346
347```cpp
Brett Wilson508162c2017-09-27 22:24:46348base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world");
tzik703f1562016-09-02 07:36:55349```
350
Matt Giuca7e81b22e2019-12-12 02:41:21351### Partial Binding Of Parameters
tzik703f1562016-09-02 07:36:55352
tzika4313512016-09-06 06:51:12353You can specify some parameters when you create the callback, and specify the
354rest when you execute the callback.
tzik703f1562016-09-02 07:36:55355
tzik703f1562016-09-02 07:36:55356When calling a function bound parameters are first, followed by unbound
357parameters.
358
Gabriel Charette90480312018-02-16 15:10:05359```cpp
360void ReadIntFromFile(const std::string& filename,
361 base::OnceCallback<void(int)> on_read);
362
363void DisplayIntWithPrefix(const std::string& prefix, int result) {
364 LOG(INFO) << prefix << result;
365}
366
367void AnotherFunc(const std::string& file) {
368 ReadIntFromFile(file, base::BindOnce(&DisplayIntWithPrefix, "MyPrefix: "));
369};
370```
371
Matt Giuca7e81b22e2019-12-12 02:41:21372This technique is known as [partial
373application](http://en.wikipedia.org/wiki/Partial_application). It should be
374used in lieu of creating an adapter class that holds the bound arguments. Notice
375also that the `"MyPrefix: "` argument is actually a `const char*`, while
376`DisplayIntWithPrefix` actually wants a `const std::string&`. Like normal
377function dispatch, `base::Bind`, will coerce parameter types if possible.
Gabriel Charette90480312018-02-16 15:10:05378
Max Morinb51cf512018-02-19 12:49:49379### Avoiding Copies With Callback Parameters
tzik7c0c0cf12016-10-05 08:14:05380
Max Morinb51cf512018-02-19 12:49:49381A parameter of `base::BindRepeating()` or `base::BindOnce()` is moved into its
382internal storage if it is passed as a rvalue.
tzik7c0c0cf12016-10-05 08:14:05383
384```cpp
385std::vector<int> v = {1, 2, 3};
386// |v| is moved into the internal storage without copy.
Brett Wilson508162c2017-09-27 22:24:46387base::Bind(&Foo, std::move(v));
tzik7c0c0cf12016-10-05 08:14:05388```
389
390```cpp
tzik7c0c0cf12016-10-05 08:14:05391// The vector is moved into the internal storage without copy.
Brett Wilson508162c2017-09-27 22:24:46392base::Bind(&Foo, std::vector<int>({1, 2, 3}));
tzik7c0c0cf12016-10-05 08:14:05393```
394
Max Morinb51cf512018-02-19 12:49:49395Arguments bound with `base::BindOnce()` are always moved, if possible, to the
396target function.
397A function parameter that is passed by value and has a move constructor will be
398moved instead of copied.
399This makes it easy to use move-only types with `base::BindOnce()`.
400
401In contrast, arguments bound with `base::BindRepeating()` are only moved to the
402target function if the argument is bound with `base::Passed()`.
403
404**DANGER**:
405A `base::RepeatingCallback` can only be run once if arguments were bound with
406`base::Passed()`.
407For this reason, avoid `base::Passed()`.
408If you know a callback will only be called once, prefer to refactor code to
409work with `base::OnceCallback` instead.
410
411Avoid using `base::Passed()` with `base::BindOnce()`, as `std::move()` does the
412same thing and is more familiar.
tzik7c0c0cf12016-10-05 08:14:05413
414```cpp
415void Foo(std::unique_ptr<int>) {}
Max Morinb51cf512018-02-19 12:49:49416auto p = std::make_unique<int>(42);
tzik7c0c0cf12016-10-05 08:14:05417
418// |p| is moved into the internal storage of Bind(), and moved out to |Foo|.
Brett Wilson508162c2017-09-27 22:24:46419base::BindOnce(&Foo, std::move(p));
Max Morinb51cf512018-02-19 12:49:49420base::BindRepeating(&Foo, base::Passed(&p)); // Ok, but subtle.
421base::BindRepeating(&Foo, base::Passed(std::move(p))); // Ok, but subtle.
tzik7c0c0cf12016-10-05 08:14:05422```
423
tzika4313512016-09-06 06:51:12424## Quick reference for advanced binding
tzik703f1562016-09-02 07:36:55425
tzika4313512016-09-06 06:51:12426### Binding A Class Method With Weak Pointers
tzik703f1562016-09-02 07:36:55427
Wez33276262019-06-21 00:11:20428If `MyClass` has a `base::WeakPtr<MyClass> weak_this_` member (see below)
429then a class method can be bound with:
430
tzik703f1562016-09-02 07:36:55431```cpp
Wez33276262019-06-21 00:11:20432base::Bind(&MyClass::Foo, weak_this_);
tzika4313512016-09-06 06:51:12433```
tzik703f1562016-09-02 07:36:55434
435The callback will not be run if the object has already been destroyed.
Brett Wilson508162c2017-09-27 22:24:46436
Wez33276262019-06-21 00:11:20437Note that class method callbacks bound to `base::WeakPtr`s may only be
438run on the same sequence on which the object will be destroyed, since otherwise
439execution of the callback might race with the object's deletion.
440
441To use `base::WeakPtr` with `base::Bind()`, `MyClass` will typically look like:
442
443```cpp
444class MyClass {
445public:
Jeremy Roman0dd0b2f2019-07-16 21:00:43446 MyClass() {
Wez33276262019-06-21 00:11:20447 weak_this_ = weak_factory_.GetWeakPtr();
448 }
449private:
450 base::WeakPtr<MyClass> weak_this_;
451 // MyClass member variables go here.
Jeremy Roman0dd0b2f2019-07-16 21:00:43452 base::WeakPtrFactory<MyClass> weak_factory_{this};
Wez33276262019-06-21 00:11:20453};
454```
455
456`weak_factory_` is the last member variable in `MyClass` so that it is
457destroyed first. This ensures that if any class methods bound to `weak_this_`
458are `Run()` during teardown, then they will not actually be executed.
459
460If `MyClass` only ever `base::Bind()`s and executes callbacks on the same
461sequence, then it is generally safe to call `weak_factory_.GetWeakPtr()` at the
462`base::Bind()` call, rather than taking a separate `weak_this_` during
463construction.
tzik703f1562016-09-02 07:36:55464
tzika4313512016-09-06 06:51:12465### Binding A Class Method With Manual Lifetime Management
tzik703f1562016-09-02 07:36:55466
467```cpp
Brett Wilson508162c2017-09-27 22:24:46468base::Bind(&MyClass::Foo, base::Unretained(this));
tzik703f1562016-09-02 07:36:55469```
470
tzika4313512016-09-06 06:51:12471This disables all lifetime management on the object. You're responsible for
472making sure the object is alive at the time of the call. You break it, you own
473it!
tzik703f1562016-09-02 07:36:55474
tzika4313512016-09-06 06:51:12475### Binding A Class Method And Having The Callback Own The Class
tzik703f1562016-09-02 07:36:55476
477```cpp
478MyClass* myclass = new MyClass;
Brett Wilson508162c2017-09-27 22:24:46479base::Bind(&MyClass::Foo, base::Owned(myclass));
tzik703f1562016-09-02 07:36:55480```
481
tzika4313512016-09-06 06:51:12482The object will be deleted when the callback is destroyed, even if it's not run
483(like if you post a task during shutdown). Potentially useful for "fire and
484forget" cases.
tzik703f1562016-09-02 07:36:55485
tzik7c0c0cf12016-10-05 08:14:05486Smart pointers (e.g. `std::unique_ptr<>`) are also supported as the receiver.
487
488```cpp
489std::unique_ptr<MyClass> myclass(new MyClass);
Brett Wilson508162c2017-09-27 22:24:46490base::Bind(&MyClass::Foo, std::move(myclass));
tzik7c0c0cf12016-10-05 08:14:05491```
492
tzika4313512016-09-06 06:51:12493### Ignoring Return Values
tzik703f1562016-09-02 07:36:55494
tzika4313512016-09-06 06:51:12495Sometimes you want to call a function that returns a value in a callback that
496doesn't expect a return value.
tzik703f1562016-09-02 07:36:55497
498```cpp
499int DoSomething(int arg) { cout << arg << endl; }
Brett Wilson508162c2017-09-27 22:24:46500base::Callback<void(int)> cb =
501 base::Bind(IgnoreResult(&DoSomething));
tzik703f1562016-09-02 07:36:55502```
503
tzika4313512016-09-06 06:51:12504## Quick reference for binding parameters to Bind()
tzik703f1562016-09-02 07:36:55505
Brett Wilson508162c2017-09-27 22:24:46506Bound parameters are specified as arguments to `base::Bind()` and are passed to
507the function. A callback with no parameters or no unbound parameters is called
508a `base::Closure` (`base::Callback<void()>` and `base::Closure` are the same
509thing).
tzik703f1562016-09-02 07:36:55510
tzika4313512016-09-06 06:51:12511### Passing Parameters Owned By The Callback
tzik703f1562016-09-02 07:36:55512
513```cpp
514void Foo(int* arg) { cout << *arg << endl; }
515int* pn = new int(1);
Brett Wilson508162c2017-09-27 22:24:46516base::Closure foo_callback = base::Bind(&foo, base::Owned(pn));
tzik703f1562016-09-02 07:36:55517```
518
tzika4313512016-09-06 06:51:12519The parameter will be deleted when the callback is destroyed, even if it's not
520run (like if you post a task during shutdown).
tzik703f1562016-09-02 07:36:55521
tzika4313512016-09-06 06:51:12522### Passing Parameters As A unique_ptr
tzik703f1562016-09-02 07:36:55523
524```cpp
525void TakesOwnership(std::unique_ptr<Foo> arg) {}
Max Morinb51cf512018-02-19 12:49:49526auto f = std::make_unique<Foo>();
tzik703f1562016-09-02 07:36:55527// f becomes null during the following call.
Max Morinb51cf512018-02-19 12:49:49528base::OnceClosure cb = base::BindOnce(&TakesOwnership, std::move(f));
tzik703f1562016-09-02 07:36:55529```
530
tzika4313512016-09-06 06:51:12531Ownership of the parameter will be with the callback until the callback is run,
532and then ownership is passed to the callback function. This means the callback
533can only be run once. If the callback is never run, it will delete the object
534when it's destroyed.
tzik703f1562016-09-02 07:36:55535
tzika4313512016-09-06 06:51:12536### Passing Parameters As A scoped_refptr
tzik703f1562016-09-02 07:36:55537
538```cpp
539void TakesOneRef(scoped_refptr<Foo> arg) {}
tzik7c0c0cf12016-10-05 08:14:05540scoped_refptr<Foo> f(new Foo);
Brett Wilson508162c2017-09-27 22:24:46541base::Closure cb = base::Bind(&TakesOneRef, f);
tzik703f1562016-09-02 07:36:55542```
543
tzika4313512016-09-06 06:51:12544This should "just work." The closure will take a reference as long as it is
545alive, and another reference will be taken for the called function.
tzik703f1562016-09-02 07:36:55546
tzik7c0c0cf12016-10-05 08:14:05547```cpp
548void DontTakeRef(Foo* arg) {}
549scoped_refptr<Foo> f(new Foo);
Brett Wilson508162c2017-09-27 22:24:46550base::Closure cb = base::Bind(&DontTakeRef, base::RetainedRef(f));
tzik7c0c0cf12016-10-05 08:14:05551```
552
Brett Wilson508162c2017-09-27 22:24:46553`base::RetainedRef` holds a reference to the object and passes a raw pointer to
tzik7c0c0cf12016-10-05 08:14:05554the object when the Callback is run.
555
tzika4313512016-09-06 06:51:12556### Passing Parameters By Reference
tzik703f1562016-09-02 07:36:55557
jdoerrie9d7236f62019-03-05 13:00:23558References are *copied* unless `std::ref` or `std::cref` is used. Example:
tzik703f1562016-09-02 07:36:55559
560```cpp
561void foo(const int& arg) { printf("%d %p\n", arg, &arg); }
562int n = 1;
Brett Wilson508162c2017-09-27 22:24:46563base::Closure has_copy = base::Bind(&foo, n);
jdoerrie9d7236f62019-03-05 13:00:23564base::Closure has_ref = base::Bind(&foo, std::cref(n));
tzik703f1562016-09-02 07:36:55565n = 2;
566foo(n); // Prints "2 0xaaaaaaaaaaaa"
567has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb"
568has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa"
569```
570
tzika4313512016-09-06 06:51:12571Normally parameters are copied in the closure.
jdoerrie9d7236f62019-03-05 13:00:23572**DANGER**: `std::ref` and `std::cref` store a (const) reference instead,
573referencing the original parameter. This means that you must ensure the object
574outlives the callback!
tzik703f1562016-09-02 07:36:55575
tzika4313512016-09-06 06:51:12576## Implementation notes
tzik703f1562016-09-02 07:36:55577
tzika4313512016-09-06 06:51:12578### Where Is This Design From:
tzik703f1562016-09-02 07:36:55579
Brett Wilson508162c2017-09-27 22:24:46580The design of `base::Callback` and `base::Bind` is heavily influenced by C++'s
581`tr1::function` / `tr1::bind`, and by the "Google Callback" system used inside
582Google.
tzik703f1562016-09-02 07:36:55583
tzik7c0c0cf12016-10-05 08:14:05584### Customizing the behavior
585
Brett Wilson508162c2017-09-27 22:24:46586There are several injection points that controls binding behavior from outside
587of its implementation.
tzik7c0c0cf12016-10-05 08:14:05588
589```cpp
Brett Wilson508162c2017-09-27 22:24:46590namespace base {
591
tzik7c0c0cf12016-10-05 08:14:05592template <typename Receiver>
593struct IsWeakReceiver {
594 static constexpr bool value = false;
595};
596
597template <typename Obj>
598struct UnwrapTraits {
599 template <typename T>
600 T&& Unwrap(T&& obj) {
601 return std::forward<T>(obj);
602 }
603};
Brett Wilson508162c2017-09-27 22:24:46604
605} // namespace base
tzik7c0c0cf12016-10-05 08:14:05606```
607
Brett Wilson508162c2017-09-27 22:24:46608If `base::IsWeakReceiver<Receiver>::value` is true on a receiver of a method,
609`base::Bind` checks if the receiver is evaluated to true and cancels the invocation
610if it's evaluated to false. You can specialize `base::IsWeakReceiver` to make
611an external smart pointer as a weak pointer.
tzik7c0c0cf12016-10-05 08:14:05612
Brett Wilson508162c2017-09-27 22:24:46613`base::UnwrapTraits<BoundObject>::Unwrap()` is called for each bound arguments
jdoerrie9d7236f62019-03-05 13:00:23614right before `base::Callback` calls the target function. You can specialize this
615to define an argument wrapper such as `base::Unretained`, `base::Owned`,
616`base::RetainedRef` and `base::Passed`.
tzik7c0c0cf12016-10-05 08:14:05617
tzika4313512016-09-06 06:51:12618### How The Implementation Works:
tzik703f1562016-09-02 07:36:55619
620There are three main components to the system:
Brett Wilson508162c2017-09-27 22:24:46621 1) The `base::Callback<>` classes.
622 2) The `base::Bind()` functions.
jdoerrie9d7236f62019-03-05 13:00:23623 3) The arguments wrappers (e.g., `base::Unretained()` and `base::Owned()`).
tzik703f1562016-09-02 07:36:55624
Brett Wilson508162c2017-09-27 22:24:46625The Callback classes represent a generic function pointer. Internally, it
626stores a refcounted piece of state that represents the target function and all
627its bound parameters. The `base::Callback` constructor takes a
628`base::BindStateBase*`, which is upcasted from a `base::BindState<>`. In the
629context of the constructor, the static type of this `base::BindState<>` pointer
630uniquely identifies the function it is representing, all its bound parameters,
631and a `Run()` method that is capable of invoking the target.
tzik703f1562016-09-02 07:36:55632
Brett Wilson508162c2017-09-27 22:24:46633`base::Bind()` creates the `base::BindState<>` that has the full static type,
634and erases the target function type as well as the types of the bound
635parameters. It does this by storing a pointer to the specific `Run()` function,
636and upcasting the state of `base::BindState<>*` to a `base::BindStateBase*`.
637This is safe as long as this `BindStateBase` pointer is only used with the
638stored `Run()` pointer.
tzik703f1562016-09-02 07:36:55639
Brett Wilson508162c2017-09-27 22:24:46640To `base::BindState<>` objects are created inside the `base::Bind()` functions.
tzik703f1562016-09-02 07:36:55641These functions, along with a set of internal templates, are responsible for
642
643 - Unwrapping the function signature into return type, and parameters
644 - Determining the number of parameters that are bound
645 - Creating the BindState storing the bound parameters
646 - Performing compile-time asserts to avoid error-prone behavior
Armando Miragliacce1eb42018-08-16 14:35:44647 - Returning a `Callback<>` with an arity matching the number of unbound
tzik703f1562016-09-02 07:36:55648 parameters and that knows the correct refcounting semantics for the
649 target object if we are binding a method.
650
Brett Wilson508162c2017-09-27 22:24:46651The `base::Bind` functions do the above using type-inference and variadic
652templates.
tzik703f1562016-09-02 07:36:55653
Brett Wilson508162c2017-09-27 22:24:46654By default `base::Bind()` will store copies of all bound parameters, and
655attempt to refcount a target object if the function being bound is a class
656method. These copies are created even if the function takes parameters as const
tzik703f1562016-09-02 07:36:55657references. (Binding to non-const references is forbidden, see bind.h.)
658
tzika4313512016-09-06 06:51:12659To change this behavior, we introduce a set of argument wrappers (e.g.,
jdoerrie9d7236f62019-03-05 13:00:23660`base::Unretained()`). These are simple container templates that are passed by
661value, and wrap a pointer to argument. See the file-level comment in
662base/bind_helpers.h for more info.
tzik703f1562016-09-02 07:36:55663
tzik7c0c0cf12016-10-05 08:14:05664These types are passed to the `Unwrap()` functions to modify the behavior of
Brett Wilson508162c2017-09-27 22:24:46665`base::Bind()`. The `Unwrap()` functions change behavior by doing partial
tzik7c0c0cf12016-10-05 08:14:05666specialization based on whether or not a parameter is a wrapper type.
tzik703f1562016-09-02 07:36:55667
jdoerrie9d7236f62019-03-05 13:00:23668`base::Unretained()` is specific to Chromium.
tzik703f1562016-09-02 07:36:55669
tzika4313512016-09-06 06:51:12670### Missing Functionality
tzik703f1562016-09-02 07:36:55671 - Binding arrays to functions that take a non-const pointer.
672 Example:
673```cpp
674void Foo(const char* ptr);
675void Bar(char* ptr);
Brett Wilson508162c2017-09-27 22:24:46676base::Bind(&Foo, "test");
677base::Bind(&Bar, "test"); // This fails because ptr is not const.
tzik703f1562016-09-02 07:36:55678```
Gayane Petrosyan7f716982018-03-09 15:17:34679 - In case of partial binding of parameters a possibility of having unbound
680 parameters before bound parameters. Example:
681```cpp
682void Foo(int x, bool y);
683base::Bind(&Foo, _1, false); // _1 is a placeholder.
684```
tzik703f1562016-09-02 07:36:55685
Brett Wilson508162c2017-09-27 22:24:46686If you are thinking of forward declaring `base::Callback` in your own header
687file, please include "base/callback_forward.h" instead.