blob: 36a6b2ee3af367c7733b60a54dc72ef5d391ea62 [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
tzika4313512016-09-06 06:51:1211Partial application (or "currying") is the process of binding a subset of a
12function's arguments to produce another function that takes fewer arguments.
13This can be used to pass around a unit of delayed execution, much like lexical
14closures are used in other languages. For example, it is used in Chromium code
15to schedule tasks on different 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
Brett Wilson508162c2017-09-27 22:24:4651Pass `base::Callback` objects by value if ownership is transferred; otherwise,
52pass 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|.
Brett Wilson508162c2017-09-27 22:24:4661base::OnceCallback<void(int)> g_cb;
62void Bar(base::OnceCallback<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|.
Brett Wilson508162c2017-09-27 22:24:4673void Qux(base::OnceCallback<void(int)> cb) {
michaelpg126f704d12017-03-14 23:22:5374 PostTask(FROM_HERE,
tzik298f67a2017-04-24 06:14:1375 base::BindOnce(std::move(cb), 42));
tzik7c0c0cf12016-10-05 08:14:0576}
77```
78
Brett Wilson508162c2017-09-27 22:24:4679When you pass a `base::Callback` object to a function parameter, use
80`std::move()` if you don't need to keep a reference to it, otherwise, pass the
81object 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
83moved-from `base::Callback` becomes null, as if its `Reset()` method had been
84called, and its `is_null()` method will return true.
tzik703f1562016-09-02 07:36:5585
tzika4313512016-09-06 06:51:1286## Quick reference for basic stuff
tzik703f1562016-09-02 07:36:5587
tzika4313512016-09-06 06:51:1288### Binding A Bare Function
tzik703f1562016-09-02 07:36:5589
90```cpp
91int Return5() { return 5; }
Brett Wilson508162c2017-09-27 22:24:4692base::OnceCallback<int()> func_cb = base::BindOnce(&Return5);
tzik7c0c0cf12016-10-05 08:14:0593LOG(INFO) << std::move(func_cb).Run(); // Prints 5.
94```
95
96```cpp
97int Return5() { return 5; }
Brett Wilson508162c2017-09-27 22:24:4698base::RepeatingCallback<int()> func_cb = base::BindRepeating(&Return5);
tzik703f1562016-09-02 07:36:5599LOG(INFO) << func_cb.Run(); // Prints 5.
100```
101
tzik7c0c0cf12016-10-05 08:14:05102### Binding A Captureless Lambda
103
104```cpp
Brett Wilson508162c2017-09-27 22:24:46105base::Callback<int()> lambda_cb = base::Bind([] { return 4; });
tzik7c0c0cf12016-10-05 08:14:05106LOG(INFO) << lambda_cb.Run(); // Print 4.
107
Brett Wilson508162c2017-09-27 22:24:46108base::OnceCallback<int()> lambda_cb2 = base::BindOnce([] { return 3; });
tzik7c0c0cf12016-10-05 08:14:05109LOG(INFO) << std::move(lambda_cb2).Run(); // Print 3.
110```
111
Raphael Kubo da Costa17c1618c2019-03-28 19:30:44112### Binding A Capturing Lambda (In Tests)
113
114When writing tests, it is often useful to capture arguments that need to be
115modified in a callback.
116
117``` cpp
118#include "base/test/bind_test_util.h"
119
120int i = 2;
121base::Callback<void()> lambda_cb = base::BindLambdaForTesting([&]() { i++; });
122lambda_cb.Run();
123LOG(INFO) << i; // Print 3;
124```
125
tzika4313512016-09-06 06:51:12126### Binding A Class Method
tzik703f1562016-09-02 07:36:55127
tzika4313512016-09-06 06:51:12128The first argument to bind is the member function to call, the second is the
129object on which to call it.
tzik703f1562016-09-02 07:36:55130
131```cpp
Brett Wilson508162c2017-09-27 22:24:46132class Ref : public base::RefCountedThreadSafe<Ref> {
tzik703f1562016-09-02 07:36:55133 public:
134 int Foo() { return 3; }
tzik703f1562016-09-02 07:36:55135};
136scoped_refptr<Ref> ref = new Ref();
Brett Wilson508162c2017-09-27 22:24:46137base::Callback<void()> ref_cb = base::Bind(&Ref::Foo, ref);
tzik703f1562016-09-02 07:36:55138LOG(INFO) << ref_cb.Run(); // Prints out 3.
139```
140
141By default the object must support RefCounted or you will get a compiler
tzik7c0c0cf12016-10-05 08:14:05142error. If you're passing between threads, be sure it's RefCountedThreadSafe! See
143"Advanced binding of member functions" below if you don't want to use reference
144counting.
tzik703f1562016-09-02 07:36:55145
tzika4313512016-09-06 06:51:12146### Running A Callback
tzik703f1562016-09-02 07:36:55147
tzik7c0c0cf12016-10-05 08:14:05148Callbacks can be run with their `Run` method, which has the same signature as
Brett Wilson508162c2017-09-27 22:24:46149the template argument to the callback. Note that `base::OnceCallback::Run`
150consumes the callback object and can only be invoked on a callback rvalue.
tzik703f1562016-09-02 07:36:55151
152```cpp
Brett Wilson508162c2017-09-27 22:24:46153void DoSomething(const base::Callback<void(int, std::string)>& callback) {
tzik703f1562016-09-02 07:36:55154 callback.Run(5, "hello");
155}
tzik7c0c0cf12016-10-05 08:14:05156
Brett Wilson508162c2017-09-27 22:24:46157void DoSomethingOther(base::OnceCallback<void(int, std::string)> callback) {
tzik7c0c0cf12016-10-05 08:14:05158 std::move(callback).Run(5, "hello");
159}
tzik703f1562016-09-02 07:36:55160```
161
tzik7c0c0cf12016-10-05 08:14:05162RepeatingCallbacks can be run more than once (they don't get deleted or marked
Brett Wilson508162c2017-09-27 22:24:46163when run). However, this precludes using `base::Passed` (see below).
tzik703f1562016-09-02 07:36:55164
165```cpp
Brett Wilson508162c2017-09-27 22:24:46166void DoSomething(const base::RepeatingCallback<double(double)>& callback) {
tzik703f1562016-09-02 07:36:55167 double myresult = callback.Run(3.14159);
168 myresult += callback.Run(2.71828);
169}
170```
171
michaelpg0f156e12017-03-18 02:49:09172If running a callback could result in its own destruction (e.g., if the callback
173recipient deletes the object the callback is a member of), the callback should
Bence Béky15327452018-05-10 20:59:07174be moved before it can be safely invoked. (Note that this is only an issue for
175RepeatingCallbacks, because a OnceCallback always has to be moved for
176execution.)
michaelpg0f156e12017-03-18 02:49:09177
178```cpp
179void Foo::RunCallback() {
Bence Béky15327452018-05-10 20:59:07180 std::move(&foo_deleter_callback_).Run();
michaelpg0f156e12017-03-18 02:49:09181}
182```
183
Peter Kasting341e1fb2018-02-24 00:03:01184### Creating a Callback That Does Nothing
185
186Sometimes you need a callback that does nothing when run (e.g. test code that
187doesn't care to be notified about certain types of events). It may be tempting
188to pass a default-constructed callback of the right type:
189
190```cpp
191using MyCallback = base::OnceCallback<void(bool arg)>;
192void MyFunction(MyCallback callback) {
193 std::move(callback).Run(true); // Uh oh...
194}
195...
196MyFunction(MyCallback()); // ...this will crash when Run()!
197```
198
199Default-constructed callbacks are null, and thus cannot be Run(). Instead, use
200`base::DoNothing()`:
201
202```cpp
203...
204MyFunction(base::DoNothing()); // Can be Run(), will no-op
205```
206
207`base::DoNothing()` can be passed for any OnceCallback or RepeatingCallback that
208returns void.
209
210Implementation-wise, `base::DoNothing()` is actually a functor which produces a
211callback from `operator()`. This makes it unusable when trying to bind other
212arguments to it. Normally, the only reason to bind arguments to DoNothing() is
213to manage object lifetimes, and in these cases, you should strive to use idioms
214like DeleteSoon(), ReleaseSoon(), or RefCountedDeleteOnSequence instead. If you
215truly need to bind an argument to DoNothing(), or if you need to explicitly
216create a callback object (because implicit conversion through operator()() won't
217compile), you can instantiate directly:
218
219```cpp
220// Binds |foo_ptr| to a no-op OnceCallback takes a scoped_refptr<Foo>.
221// ANTIPATTERN WARNING: This should likely be changed to ReleaseSoon()!
222base::Bind(base::DoNothing::Once<scoped_refptr<Foo>>(), foo_ptr);
223```
224
tzika4313512016-09-06 06:51:12225### Passing Unbound Input Parameters
tzik703f1562016-09-02 07:36:55226
227Unbound parameters are specified at the time a callback is `Run()`. They are
Brett Wilson508162c2017-09-27 22:24:46228specified in the `base::Callback` template type:
tzik703f1562016-09-02 07:36:55229
230```cpp
231void MyFunc(int i, const std::string& str) {}
Brett Wilson508162c2017-09-27 22:24:46232base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc);
tzik703f1562016-09-02 07:36:55233cb.Run(23, "hello, world");
234```
235
tzika4313512016-09-06 06:51:12236### Passing Bound Input Parameters
tzik703f1562016-09-02 07:36:55237
tzika4313512016-09-06 06:51:12238Bound parameters are specified when you create the callback as arguments to
Brett Wilson508162c2017-09-27 22:24:46239`base::Bind()`. They will be passed to the function and the `Run()`ner of the
240callback doesn't see those values or even know that the function it's calling.
tzik703f1562016-09-02 07:36:55241
242```cpp
243void MyFunc(int i, const std::string& str) {}
Brett Wilson508162c2017-09-27 22:24:46244base::Callback<void()> cb = base::Bind(&MyFunc, 23, "hello world");
tzik703f1562016-09-02 07:36:55245cb.Run();
246```
247
Brett Wilson508162c2017-09-27 22:24:46248A callback with no unbound input parameters (`base::Callback<void()>`) is
249called a `base::Closure`. So we could have also written:
tzik703f1562016-09-02 07:36:55250
251```cpp
Brett Wilson508162c2017-09-27 22:24:46252base::Closure cb = base::Bind(&MyFunc, 23, "hello world");
tzik703f1562016-09-02 07:36:55253```
254
255When calling member functions, bound parameters just go after the object
256pointer.
257
258```cpp
Brett Wilson508162c2017-09-27 22:24:46259base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world");
tzik703f1562016-09-02 07:36:55260```
261
Gabriel Charette90480312018-02-16 15:10:05262### Partial Binding Of Parameters (Currying)
tzik703f1562016-09-02 07:36:55263
tzika4313512016-09-06 06:51:12264You can specify some parameters when you create the callback, and specify the
265rest when you execute the callback.
tzik703f1562016-09-02 07:36:55266
tzik703f1562016-09-02 07:36:55267When calling a function bound parameters are first, followed by unbound
268parameters.
269
Gabriel Charette90480312018-02-16 15:10:05270```cpp
271void ReadIntFromFile(const std::string& filename,
272 base::OnceCallback<void(int)> on_read);
273
274void DisplayIntWithPrefix(const std::string& prefix, int result) {
275 LOG(INFO) << prefix << result;
276}
277
278void AnotherFunc(const std::string& file) {
279 ReadIntFromFile(file, base::BindOnce(&DisplayIntWithPrefix, "MyPrefix: "));
280};
281```
282
283This technique is known as [Currying](http://en.wikipedia.org/wiki/Currying). It
284should be used in lieu of creating an adapter class that holds the bound
285arguments. Notice also that the `"MyPrefix: "` argument is actually a
286`const char*`, while `DisplayIntWithPrefix` actually wants a
287`const std::string&`. Like normal function dispatch, `base::Bind`, will coerce
288parameter types if possible.
289
Max Morinb51cf512018-02-19 12:49:49290### Avoiding Copies With Callback Parameters
tzik7c0c0cf12016-10-05 08:14:05291
Max Morinb51cf512018-02-19 12:49:49292A parameter of `base::BindRepeating()` or `base::BindOnce()` is moved into its
293internal storage if it is passed as a rvalue.
tzik7c0c0cf12016-10-05 08:14:05294
295```cpp
296std::vector<int> v = {1, 2, 3};
297// |v| is moved into the internal storage without copy.
Brett Wilson508162c2017-09-27 22:24:46298base::Bind(&Foo, std::move(v));
tzik7c0c0cf12016-10-05 08:14:05299```
300
301```cpp
tzik7c0c0cf12016-10-05 08:14:05302// The vector is moved into the internal storage without copy.
Brett Wilson508162c2017-09-27 22:24:46303base::Bind(&Foo, std::vector<int>({1, 2, 3}));
tzik7c0c0cf12016-10-05 08:14:05304```
305
Max Morinb51cf512018-02-19 12:49:49306Arguments bound with `base::BindOnce()` are always moved, if possible, to the
307target function.
308A function parameter that is passed by value and has a move constructor will be
309moved instead of copied.
310This makes it easy to use move-only types with `base::BindOnce()`.
311
312In contrast, arguments bound with `base::BindRepeating()` are only moved to the
313target function if the argument is bound with `base::Passed()`.
314
315**DANGER**:
316A `base::RepeatingCallback` can only be run once if arguments were bound with
317`base::Passed()`.
318For this reason, avoid `base::Passed()`.
319If you know a callback will only be called once, prefer to refactor code to
320work with `base::OnceCallback` instead.
321
322Avoid using `base::Passed()` with `base::BindOnce()`, as `std::move()` does the
323same thing and is more familiar.
tzik7c0c0cf12016-10-05 08:14:05324
325```cpp
326void Foo(std::unique_ptr<int>) {}
Max Morinb51cf512018-02-19 12:49:49327auto p = std::make_unique<int>(42);
tzik7c0c0cf12016-10-05 08:14:05328
329// |p| is moved into the internal storage of Bind(), and moved out to |Foo|.
Brett Wilson508162c2017-09-27 22:24:46330base::BindOnce(&Foo, std::move(p));
Max Morinb51cf512018-02-19 12:49:49331base::BindRepeating(&Foo, base::Passed(&p)); // Ok, but subtle.
332base::BindRepeating(&Foo, base::Passed(std::move(p))); // Ok, but subtle.
tzik7c0c0cf12016-10-05 08:14:05333```
334
tzika4313512016-09-06 06:51:12335## Quick reference for advanced binding
tzik703f1562016-09-02 07:36:55336
tzika4313512016-09-06 06:51:12337### Binding A Class Method With Weak Pointers
tzik703f1562016-09-02 07:36:55338
339```cpp
Brett Wilson508162c2017-09-27 22:24:46340base::Bind(&MyClass::Foo, GetWeakPtr());
tzika4313512016-09-06 06:51:12341```
tzik703f1562016-09-02 07:36:55342
343The callback will not be run if the object has already been destroyed.
Brett Wilson508162c2017-09-27 22:24:46344**DANGER**: weak pointers are not threadsafe, so don't use this when passing
345between threads!
346
347To make a weak pointer, you would typically create a
348`base::WeakPtrFactory<Foo>` member at the bottom (to ensure it's destroyed
349last) of class `Foo`, then call `weak_factory_.GetWeakPtr()`.
tzik703f1562016-09-02 07:36:55350
tzika4313512016-09-06 06:51:12351### Binding A Class Method With Manual Lifetime Management
tzik703f1562016-09-02 07:36:55352
353```cpp
Brett Wilson508162c2017-09-27 22:24:46354base::Bind(&MyClass::Foo, base::Unretained(this));
tzik703f1562016-09-02 07:36:55355```
356
tzika4313512016-09-06 06:51:12357This disables all lifetime management on the object. You're responsible for
358making sure the object is alive at the time of the call. You break it, you own
359it!
tzik703f1562016-09-02 07:36:55360
tzika4313512016-09-06 06:51:12361### Binding A Class Method And Having The Callback Own The Class
tzik703f1562016-09-02 07:36:55362
363```cpp
364MyClass* myclass = new MyClass;
Brett Wilson508162c2017-09-27 22:24:46365base::Bind(&MyClass::Foo, base::Owned(myclass));
tzik703f1562016-09-02 07:36:55366```
367
tzika4313512016-09-06 06:51:12368The object will be deleted when the callback is destroyed, even if it's not run
369(like if you post a task during shutdown). Potentially useful for "fire and
370forget" cases.
tzik703f1562016-09-02 07:36:55371
tzik7c0c0cf12016-10-05 08:14:05372Smart pointers (e.g. `std::unique_ptr<>`) are also supported as the receiver.
373
374```cpp
375std::unique_ptr<MyClass> myclass(new MyClass);
Brett Wilson508162c2017-09-27 22:24:46376base::Bind(&MyClass::Foo, std::move(myclass));
tzik7c0c0cf12016-10-05 08:14:05377```
378
tzika4313512016-09-06 06:51:12379### Ignoring Return Values
tzik703f1562016-09-02 07:36:55380
tzika4313512016-09-06 06:51:12381Sometimes you want to call a function that returns a value in a callback that
382doesn't expect a return value.
tzik703f1562016-09-02 07:36:55383
384```cpp
385int DoSomething(int arg) { cout << arg << endl; }
Brett Wilson508162c2017-09-27 22:24:46386base::Callback<void(int)> cb =
387 base::Bind(IgnoreResult(&DoSomething));
tzik703f1562016-09-02 07:36:55388```
389
tzika4313512016-09-06 06:51:12390## Quick reference for binding parameters to Bind()
tzik703f1562016-09-02 07:36:55391
Brett Wilson508162c2017-09-27 22:24:46392Bound parameters are specified as arguments to `base::Bind()` and are passed to
393the function. A callback with no parameters or no unbound parameters is called
394a `base::Closure` (`base::Callback<void()>` and `base::Closure` are the same
395thing).
tzik703f1562016-09-02 07:36:55396
tzika4313512016-09-06 06:51:12397### Passing Parameters Owned By The Callback
tzik703f1562016-09-02 07:36:55398
399```cpp
400void Foo(int* arg) { cout << *arg << endl; }
401int* pn = new int(1);
Brett Wilson508162c2017-09-27 22:24:46402base::Closure foo_callback = base::Bind(&foo, base::Owned(pn));
tzik703f1562016-09-02 07:36:55403```
404
tzika4313512016-09-06 06:51:12405The parameter will be deleted when the callback is destroyed, even if it's not
406run (like if you post a task during shutdown).
tzik703f1562016-09-02 07:36:55407
tzika4313512016-09-06 06:51:12408### Passing Parameters As A unique_ptr
tzik703f1562016-09-02 07:36:55409
410```cpp
411void TakesOwnership(std::unique_ptr<Foo> arg) {}
Max Morinb51cf512018-02-19 12:49:49412auto f = std::make_unique<Foo>();
tzik703f1562016-09-02 07:36:55413// f becomes null during the following call.
Max Morinb51cf512018-02-19 12:49:49414base::OnceClosure cb = base::BindOnce(&TakesOwnership, std::move(f));
tzik703f1562016-09-02 07:36:55415```
416
tzika4313512016-09-06 06:51:12417Ownership of the parameter will be with the callback until the callback is run,
418and then ownership is passed to the callback function. This means the callback
419can only be run once. If the callback is never run, it will delete the object
420when it's destroyed.
tzik703f1562016-09-02 07:36:55421
tzika4313512016-09-06 06:51:12422### Passing Parameters As A scoped_refptr
tzik703f1562016-09-02 07:36:55423
424```cpp
425void TakesOneRef(scoped_refptr<Foo> arg) {}
tzik7c0c0cf12016-10-05 08:14:05426scoped_refptr<Foo> f(new Foo);
Brett Wilson508162c2017-09-27 22:24:46427base::Closure cb = base::Bind(&TakesOneRef, f);
tzik703f1562016-09-02 07:36:55428```
429
tzika4313512016-09-06 06:51:12430This should "just work." The closure will take a reference as long as it is
431alive, and another reference will be taken for the called function.
tzik703f1562016-09-02 07:36:55432
tzik7c0c0cf12016-10-05 08:14:05433```cpp
434void DontTakeRef(Foo* arg) {}
435scoped_refptr<Foo> f(new Foo);
Brett Wilson508162c2017-09-27 22:24:46436base::Closure cb = base::Bind(&DontTakeRef, base::RetainedRef(f));
tzik7c0c0cf12016-10-05 08:14:05437```
438
Brett Wilson508162c2017-09-27 22:24:46439`base::RetainedRef` holds a reference to the object and passes a raw pointer to
tzik7c0c0cf12016-10-05 08:14:05440the object when the Callback is run.
441
tzika4313512016-09-06 06:51:12442### Passing Parameters By Reference
tzik703f1562016-09-02 07:36:55443
jdoerrie9d7236f62019-03-05 13:00:23444References are *copied* unless `std::ref` or `std::cref` is used. Example:
tzik703f1562016-09-02 07:36:55445
446```cpp
447void foo(const int& arg) { printf("%d %p\n", arg, &arg); }
448int n = 1;
Brett Wilson508162c2017-09-27 22:24:46449base::Closure has_copy = base::Bind(&foo, n);
jdoerrie9d7236f62019-03-05 13:00:23450base::Closure has_ref = base::Bind(&foo, std::cref(n));
tzik703f1562016-09-02 07:36:55451n = 2;
452foo(n); // Prints "2 0xaaaaaaaaaaaa"
453has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb"
454has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa"
455```
456
tzika4313512016-09-06 06:51:12457Normally parameters are copied in the closure.
jdoerrie9d7236f62019-03-05 13:00:23458**DANGER**: `std::ref` and `std::cref` store a (const) reference instead,
459referencing the original parameter. This means that you must ensure the object
460outlives the callback!
tzik703f1562016-09-02 07:36:55461
tzika4313512016-09-06 06:51:12462## Implementation notes
tzik703f1562016-09-02 07:36:55463
tzika4313512016-09-06 06:51:12464### Where Is This Design From:
tzik703f1562016-09-02 07:36:55465
Brett Wilson508162c2017-09-27 22:24:46466The design of `base::Callback` and `base::Bind` is heavily influenced by C++'s
467`tr1::function` / `tr1::bind`, and by the "Google Callback" system used inside
468Google.
tzik703f1562016-09-02 07:36:55469
tzik7c0c0cf12016-10-05 08:14:05470### Customizing the behavior
471
Brett Wilson508162c2017-09-27 22:24:46472There are several injection points that controls binding behavior from outside
473of its implementation.
tzik7c0c0cf12016-10-05 08:14:05474
475```cpp
Brett Wilson508162c2017-09-27 22:24:46476namespace base {
477
tzik7c0c0cf12016-10-05 08:14:05478template <typename Receiver>
479struct IsWeakReceiver {
480 static constexpr bool value = false;
481};
482
483template <typename Obj>
484struct UnwrapTraits {
485 template <typename T>
486 T&& Unwrap(T&& obj) {
487 return std::forward<T>(obj);
488 }
489};
Brett Wilson508162c2017-09-27 22:24:46490
491} // namespace base
tzik7c0c0cf12016-10-05 08:14:05492```
493
Brett Wilson508162c2017-09-27 22:24:46494If `base::IsWeakReceiver<Receiver>::value` is true on a receiver of a method,
495`base::Bind` checks if the receiver is evaluated to true and cancels the invocation
496if it's evaluated to false. You can specialize `base::IsWeakReceiver` to make
497an external smart pointer as a weak pointer.
tzik7c0c0cf12016-10-05 08:14:05498
Brett Wilson508162c2017-09-27 22:24:46499`base::UnwrapTraits<BoundObject>::Unwrap()` is called for each bound arguments
jdoerrie9d7236f62019-03-05 13:00:23500right before `base::Callback` calls the target function. You can specialize this
501to define an argument wrapper such as `base::Unretained`, `base::Owned`,
502`base::RetainedRef` and `base::Passed`.
tzik7c0c0cf12016-10-05 08:14:05503
tzika4313512016-09-06 06:51:12504### How The Implementation Works:
tzik703f1562016-09-02 07:36:55505
506There are three main components to the system:
Brett Wilson508162c2017-09-27 22:24:46507 1) The `base::Callback<>` classes.
508 2) The `base::Bind()` functions.
jdoerrie9d7236f62019-03-05 13:00:23509 3) The arguments wrappers (e.g., `base::Unretained()` and `base::Owned()`).
tzik703f1562016-09-02 07:36:55510
Brett Wilson508162c2017-09-27 22:24:46511The Callback classes represent a generic function pointer. Internally, it
512stores a refcounted piece of state that represents the target function and all
513its bound parameters. The `base::Callback` constructor takes a
514`base::BindStateBase*`, which is upcasted from a `base::BindState<>`. In the
515context of the constructor, the static type of this `base::BindState<>` pointer
516uniquely identifies the function it is representing, all its bound parameters,
517and a `Run()` method that is capable of invoking the target.
tzik703f1562016-09-02 07:36:55518
Brett Wilson508162c2017-09-27 22:24:46519`base::Bind()` creates the `base::BindState<>` that has the full static type,
520and erases the target function type as well as the types of the bound
521parameters. It does this by storing a pointer to the specific `Run()` function,
522and upcasting the state of `base::BindState<>*` to a `base::BindStateBase*`.
523This is safe as long as this `BindStateBase` pointer is only used with the
524stored `Run()` pointer.
tzik703f1562016-09-02 07:36:55525
Brett Wilson508162c2017-09-27 22:24:46526To `base::BindState<>` objects are created inside the `base::Bind()` functions.
tzik703f1562016-09-02 07:36:55527These functions, along with a set of internal templates, are responsible for
528
529 - Unwrapping the function signature into return type, and parameters
530 - Determining the number of parameters that are bound
531 - Creating the BindState storing the bound parameters
532 - Performing compile-time asserts to avoid error-prone behavior
Armando Miragliacce1eb42018-08-16 14:35:44533 - Returning a `Callback<>` with an arity matching the number of unbound
tzik703f1562016-09-02 07:36:55534 parameters and that knows the correct refcounting semantics for the
535 target object if we are binding a method.
536
Brett Wilson508162c2017-09-27 22:24:46537The `base::Bind` functions do the above using type-inference and variadic
538templates.
tzik703f1562016-09-02 07:36:55539
Brett Wilson508162c2017-09-27 22:24:46540By default `base::Bind()` will store copies of all bound parameters, and
541attempt to refcount a target object if the function being bound is a class
542method. These copies are created even if the function takes parameters as const
tzik703f1562016-09-02 07:36:55543references. (Binding to non-const references is forbidden, see bind.h.)
544
tzika4313512016-09-06 06:51:12545To change this behavior, we introduce a set of argument wrappers (e.g.,
jdoerrie9d7236f62019-03-05 13:00:23546`base::Unretained()`). These are simple container templates that are passed by
547value, and wrap a pointer to argument. See the file-level comment in
548base/bind_helpers.h for more info.
tzik703f1562016-09-02 07:36:55549
tzik7c0c0cf12016-10-05 08:14:05550These types are passed to the `Unwrap()` functions to modify the behavior of
Brett Wilson508162c2017-09-27 22:24:46551`base::Bind()`. The `Unwrap()` functions change behavior by doing partial
tzik7c0c0cf12016-10-05 08:14:05552specialization based on whether or not a parameter is a wrapper type.
tzik703f1562016-09-02 07:36:55553
jdoerrie9d7236f62019-03-05 13:00:23554`base::Unretained()` is specific to Chromium.
tzik703f1562016-09-02 07:36:55555
tzika4313512016-09-06 06:51:12556### Missing Functionality
tzik703f1562016-09-02 07:36:55557 - Binding arrays to functions that take a non-const pointer.
558 Example:
559```cpp
560void Foo(const char* ptr);
561void Bar(char* ptr);
Brett Wilson508162c2017-09-27 22:24:46562base::Bind(&Foo, "test");
563base::Bind(&Bar, "test"); // This fails because ptr is not const.
tzik703f1562016-09-02 07:36:55564```
Gayane Petrosyan7f716982018-03-09 15:17:34565 - In case of partial binding of parameters a possibility of having unbound
566 parameters before bound parameters. Example:
567```cpp
568void Foo(int x, bool y);
569base::Bind(&Foo, _1, false); // _1 is a placeholder.
570```
tzik703f1562016-09-02 07:36:55571
Brett Wilson508162c2017-09-27 22:24:46572If you are thinking of forward declaring `base::Callback` in your own header
573file, please include "base/callback_forward.h" instead.