blob: 8bc036066f5434fb93e7d94ad3be2d3fe02c2a63 [file] [log] [blame] [view]
tzik7c0c0cf12016-10-05 08:14:051# Callback<> and Bind()
tzik703f1562016-09-02 07:36:552
tzika4313512016-09-06 06:51:123## Introduction
tzik703f1562016-09-02 07:36:554
Brett Wilson508162c2017-09-27 22:24:465The templated `base::Callback<>` class is a generalized function object.
6Together with the `base::Bind()` function in base/bind.h, they provide a
7type-safe method for performing partial application of functions.
tzik703f1562016-09-02 07:36:558
tzika4313512016-09-06 06:51:129Partial application (or "currying") is the process of binding a subset of a
10function's arguments to produce another function that takes fewer arguments.
11This can be used to pass around a unit of delayed execution, much like lexical
12closures are used in other languages. For example, it is used in Chromium code
13to schedule tasks on different MessageLoops.
tzik703f1562016-09-02 07:36:5514
Brett Wilson508162c2017-09-27 22:24:4615A callback with no unbound input parameters (`base::Callback<void()>`) is
16called a `base::Closure`. Note that this is NOT the same as what other
17languages refer to as a closure -- it does not retain a reference to its
18enclosing environment.
tzik703f1562016-09-02 07:36:5519
tzik7c0c0cf12016-10-05 08:14:0520### OnceCallback<> And RepeatingCallback<>
21
Brett Wilson508162c2017-09-27 22:24:4622`base::OnceCallback<>` and `base::RepeatingCallback<>` are next gen callback
23classes, which are under development.
tzik7c0c0cf12016-10-05 08:14:0524
Brett Wilson508162c2017-09-27 22:24:4625`base::OnceCallback<>` is created by `base::BindOnce()`. This is a callback
26variant that is a move-only type and can be run only once. This moves out bound
27parameters from its internal storage to the bound function by default, so it's
28easier to use with movable types. This should be the preferred callback type:
29since the lifetime of the callback is clear, it's simpler to reason about when
30a callback that is passed between threads is destroyed.
tzik7c0c0cf12016-10-05 08:14:0531
Brett Wilson508162c2017-09-27 22:24:4632`base::RepeatingCallback<>` is created by `base::BindRepeating()`. This is a
33callback variant that is copyable that can be run multiple times. It uses
34internal ref-counting to make copies cheap. However, since ownership is shared,
35it is harder to reason about when the callback and the bound state are
36destroyed, especially when the callback is passed between threads.
tzik7c0c0cf12016-10-05 08:14:0537
Brett Wilson508162c2017-09-27 22:24:4638The legacy `base::Callback<>` is currently aliased to
39`base::RepeatingCallback<>`. In new code, prefer `base::OnceCallback<>` where
40possible, and use `base::RepeatingCallback<>` otherwise. Once the migration is
41complete, the type alias will be removed and `base::OnceCallback<>` will be renamed
42to `base::Callback<>` to emphasize that it should be preferred.
tzik7c0c0cf12016-10-05 08:14:0543
Brett Wilson508162c2017-09-27 22:24:4644`base::RepeatingCallback<>` is convertible to `base::OnceCallback<>` by the
45implicit conversion.
tzik7c0c0cf12016-10-05 08:14:0546
tzika4313512016-09-06 06:51:1247### Memory Management And Passing
tzik703f1562016-09-02 07:36:5548
Brett Wilson508162c2017-09-27 22:24:4649Pass `base::Callback` objects by value if ownership is transferred; otherwise,
50pass it by const-reference.
tzik703f1562016-09-02 07:36:5551
tzik7c0c0cf12016-10-05 08:14:0552```cpp
53// |Foo| just refers to |cb| but doesn't store it nor consume it.
Brett Wilson508162c2017-09-27 22:24:4654bool Foo(const base::OnceCallback<void(int)>& cb) {
tzik7c0c0cf12016-10-05 08:14:0555 return cb.is_null();
56}
57
58// |Bar| takes the ownership of |cb| and stores |cb| into |g_cb|.
Brett Wilson508162c2017-09-27 22:24:4659base::OnceCallback<void(int)> g_cb;
60void Bar(base::OnceCallback<void(int)> cb) {
tzik7c0c0cf12016-10-05 08:14:0561 g_cb = std::move(cb);
62}
63
64// |Baz| takes the ownership of |cb| and consumes |cb| by Run().
Brett Wilson508162c2017-09-27 22:24:4665void Baz(base::OnceCallback<void(int)> cb) {
tzik7c0c0cf12016-10-05 08:14:0566 std::move(cb).Run(42);
67}
68
69// |Qux| takes the ownership of |cb| and transfers ownership to PostTask(),
70// which also takes the ownership of |cb|.
Brett Wilson508162c2017-09-27 22:24:4671void Qux(base::OnceCallback<void(int)> cb) {
michaelpg126f704d12017-03-14 23:22:5372 PostTask(FROM_HERE,
tzik298f67a2017-04-24 06:14:1373 base::BindOnce(std::move(cb), 42));
tzik7c0c0cf12016-10-05 08:14:0574}
75```
76
Brett Wilson508162c2017-09-27 22:24:4677When you pass a `base::Callback` object to a function parameter, use
78`std::move()` if you don't need to keep a reference to it, otherwise, pass the
79object directly. You may see a compile error when the function requires the
80exclusive ownership, and you didn't pass the callback by move. Note that the
81moved-from `base::Callback` becomes null, as if its `Reset()` method had been
82called, and its `is_null()` method will return true.
tzik703f1562016-09-02 07:36:5583
tzika4313512016-09-06 06:51:1284## Quick reference for basic stuff
tzik703f1562016-09-02 07:36:5585
tzika4313512016-09-06 06:51:1286### Binding A Bare Function
tzik703f1562016-09-02 07:36:5587
88```cpp
89int Return5() { return 5; }
Brett Wilson508162c2017-09-27 22:24:4690base::OnceCallback<int()> func_cb = base::BindOnce(&Return5);
tzik7c0c0cf12016-10-05 08:14:0591LOG(INFO) << std::move(func_cb).Run(); // Prints 5.
92```
93
94```cpp
95int Return5() { return 5; }
Brett Wilson508162c2017-09-27 22:24:4696base::RepeatingCallback<int()> func_cb = base::BindRepeating(&Return5);
tzik703f1562016-09-02 07:36:5597LOG(INFO) << func_cb.Run(); // Prints 5.
98```
99
tzik7c0c0cf12016-10-05 08:14:05100### Binding A Captureless Lambda
101
102```cpp
Brett Wilson508162c2017-09-27 22:24:46103base::Callback<int()> lambda_cb = base::Bind([] { return 4; });
tzik7c0c0cf12016-10-05 08:14:05104LOG(INFO) << lambda_cb.Run(); // Print 4.
105
Brett Wilson508162c2017-09-27 22:24:46106base::OnceCallback<int()> lambda_cb2 = base::BindOnce([] { return 3; });
tzik7c0c0cf12016-10-05 08:14:05107LOG(INFO) << std::move(lambda_cb2).Run(); // Print 3.
108```
109
tzika4313512016-09-06 06:51:12110### Binding A Class Method
tzik703f1562016-09-02 07:36:55111
tzika4313512016-09-06 06:51:12112The first argument to bind is the member function to call, the second is the
113object on which to call it.
tzik703f1562016-09-02 07:36:55114
115```cpp
Brett Wilson508162c2017-09-27 22:24:46116class Ref : public base::RefCountedThreadSafe<Ref> {
tzik703f1562016-09-02 07:36:55117 public:
118 int Foo() { return 3; }
tzik703f1562016-09-02 07:36:55119};
120scoped_refptr<Ref> ref = new Ref();
Brett Wilson508162c2017-09-27 22:24:46121base::Callback<void()> ref_cb = base::Bind(&Ref::Foo, ref);
tzik703f1562016-09-02 07:36:55122LOG(INFO) << ref_cb.Run(); // Prints out 3.
123```
124
125By default the object must support RefCounted or you will get a compiler
tzik7c0c0cf12016-10-05 08:14:05126error. If you're passing between threads, be sure it's RefCountedThreadSafe! See
127"Advanced binding of member functions" below if you don't want to use reference
128counting.
tzik703f1562016-09-02 07:36:55129
tzika4313512016-09-06 06:51:12130### Running A Callback
tzik703f1562016-09-02 07:36:55131
tzik7c0c0cf12016-10-05 08:14:05132Callbacks can be run with their `Run` method, which has the same signature as
Brett Wilson508162c2017-09-27 22:24:46133the template argument to the callback. Note that `base::OnceCallback::Run`
134consumes the callback object and can only be invoked on a callback rvalue.
tzik703f1562016-09-02 07:36:55135
136```cpp
Brett Wilson508162c2017-09-27 22:24:46137void DoSomething(const base::Callback<void(int, std::string)>& callback) {
tzik703f1562016-09-02 07:36:55138 callback.Run(5, "hello");
139}
tzik7c0c0cf12016-10-05 08:14:05140
Brett Wilson508162c2017-09-27 22:24:46141void DoSomethingOther(base::OnceCallback<void(int, std::string)> callback) {
tzik7c0c0cf12016-10-05 08:14:05142 std::move(callback).Run(5, "hello");
143}
tzik703f1562016-09-02 07:36:55144```
145
tzik7c0c0cf12016-10-05 08:14:05146RepeatingCallbacks can be run more than once (they don't get deleted or marked
Brett Wilson508162c2017-09-27 22:24:46147when run). However, this precludes using `base::Passed` (see below).
tzik703f1562016-09-02 07:36:55148
149```cpp
Brett Wilson508162c2017-09-27 22:24:46150void DoSomething(const base::RepeatingCallback<double(double)>& callback) {
tzik703f1562016-09-02 07:36:55151 double myresult = callback.Run(3.14159);
152 myresult += callback.Run(2.71828);
153}
154```
155
michaelpg0f156e12017-03-18 02:49:09156If running a callback could result in its own destruction (e.g., if the callback
157recipient deletes the object the callback is a member of), the callback should
Bence Béky15327452018-05-10 20:59:07158be moved before it can be safely invoked. (Note that this is only an issue for
159RepeatingCallbacks, because a OnceCallback always has to be moved for
160execution.)
michaelpg0f156e12017-03-18 02:49:09161
162```cpp
163void Foo::RunCallback() {
Bence Béky15327452018-05-10 20:59:07164 std::move(&foo_deleter_callback_).Run();
michaelpg0f156e12017-03-18 02:49:09165}
166```
167
Peter Kasting341e1fb2018-02-24 00:03:01168### Creating a Callback That Does Nothing
169
170Sometimes you need a callback that does nothing when run (e.g. test code that
171doesn't care to be notified about certain types of events). It may be tempting
172to pass a default-constructed callback of the right type:
173
174```cpp
175using MyCallback = base::OnceCallback<void(bool arg)>;
176void MyFunction(MyCallback callback) {
177 std::move(callback).Run(true); // Uh oh...
178}
179...
180MyFunction(MyCallback()); // ...this will crash when Run()!
181```
182
183Default-constructed callbacks are null, and thus cannot be Run(). Instead, use
184`base::DoNothing()`:
185
186```cpp
187...
188MyFunction(base::DoNothing()); // Can be Run(), will no-op
189```
190
191`base::DoNothing()` can be passed for any OnceCallback or RepeatingCallback that
192returns void.
193
194Implementation-wise, `base::DoNothing()` is actually a functor which produces a
195callback from `operator()`. This makes it unusable when trying to bind other
196arguments to it. Normally, the only reason to bind arguments to DoNothing() is
197to manage object lifetimes, and in these cases, you should strive to use idioms
198like DeleteSoon(), ReleaseSoon(), or RefCountedDeleteOnSequence instead. If you
199truly need to bind an argument to DoNothing(), or if you need to explicitly
200create a callback object (because implicit conversion through operator()() won't
201compile), you can instantiate directly:
202
203```cpp
204// Binds |foo_ptr| to a no-op OnceCallback takes a scoped_refptr<Foo>.
205// ANTIPATTERN WARNING: This should likely be changed to ReleaseSoon()!
206base::Bind(base::DoNothing::Once<scoped_refptr<Foo>>(), foo_ptr);
207```
208
tzika4313512016-09-06 06:51:12209### Passing Unbound Input Parameters
tzik703f1562016-09-02 07:36:55210
211Unbound parameters are specified at the time a callback is `Run()`. They are
Brett Wilson508162c2017-09-27 22:24:46212specified in the `base::Callback` template type:
tzik703f1562016-09-02 07:36:55213
214```cpp
215void MyFunc(int i, const std::string& str) {}
Brett Wilson508162c2017-09-27 22:24:46216base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc);
tzik703f1562016-09-02 07:36:55217cb.Run(23, "hello, world");
218```
219
tzika4313512016-09-06 06:51:12220### Passing Bound Input Parameters
tzik703f1562016-09-02 07:36:55221
tzika4313512016-09-06 06:51:12222Bound parameters are specified when you create the callback as arguments to
Brett Wilson508162c2017-09-27 22:24:46223`base::Bind()`. They will be passed to the function and the `Run()`ner of the
224callback doesn't see those values or even know that the function it's calling.
tzik703f1562016-09-02 07:36:55225
226```cpp
227void MyFunc(int i, const std::string& str) {}
Brett Wilson508162c2017-09-27 22:24:46228base::Callback<void()> cb = base::Bind(&MyFunc, 23, "hello world");
tzik703f1562016-09-02 07:36:55229cb.Run();
230```
231
Brett Wilson508162c2017-09-27 22:24:46232A callback with no unbound input parameters (`base::Callback<void()>`) is
233called a `base::Closure`. So we could have also written:
tzik703f1562016-09-02 07:36:55234
235```cpp
Brett Wilson508162c2017-09-27 22:24:46236base::Closure cb = base::Bind(&MyFunc, 23, "hello world");
tzik703f1562016-09-02 07:36:55237```
238
239When calling member functions, bound parameters just go after the object
240pointer.
241
242```cpp
Brett Wilson508162c2017-09-27 22:24:46243base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world");
tzik703f1562016-09-02 07:36:55244```
245
Gabriel Charette90480312018-02-16 15:10:05246### Partial Binding Of Parameters (Currying)
tzik703f1562016-09-02 07:36:55247
tzika4313512016-09-06 06:51:12248You can specify some parameters when you create the callback, and specify the
249rest when you execute the callback.
tzik703f1562016-09-02 07:36:55250
tzik703f1562016-09-02 07:36:55251When calling a function bound parameters are first, followed by unbound
252parameters.
253
Gabriel Charette90480312018-02-16 15:10:05254```cpp
255void ReadIntFromFile(const std::string& filename,
256 base::OnceCallback<void(int)> on_read);
257
258void DisplayIntWithPrefix(const std::string& prefix, int result) {
259 LOG(INFO) << prefix << result;
260}
261
262void AnotherFunc(const std::string& file) {
263 ReadIntFromFile(file, base::BindOnce(&DisplayIntWithPrefix, "MyPrefix: "));
264};
265```
266
267This technique is known as [Currying](http://en.wikipedia.org/wiki/Currying). It
268should be used in lieu of creating an adapter class that holds the bound
269arguments. Notice also that the `"MyPrefix: "` argument is actually a
270`const char*`, while `DisplayIntWithPrefix` actually wants a
271`const std::string&`. Like normal function dispatch, `base::Bind`, will coerce
272parameter types if possible.
273
Max Morinb51cf512018-02-19 12:49:49274### Avoiding Copies With Callback Parameters
tzik7c0c0cf12016-10-05 08:14:05275
Max Morinb51cf512018-02-19 12:49:49276A parameter of `base::BindRepeating()` or `base::BindOnce()` is moved into its
277internal storage if it is passed as a rvalue.
tzik7c0c0cf12016-10-05 08:14:05278
279```cpp
280std::vector<int> v = {1, 2, 3};
281// |v| is moved into the internal storage without copy.
Brett Wilson508162c2017-09-27 22:24:46282base::Bind(&Foo, std::move(v));
tzik7c0c0cf12016-10-05 08:14:05283```
284
285```cpp
tzik7c0c0cf12016-10-05 08:14:05286// The vector is moved into the internal storage without copy.
Brett Wilson508162c2017-09-27 22:24:46287base::Bind(&Foo, std::vector<int>({1, 2, 3}));
tzik7c0c0cf12016-10-05 08:14:05288```
289
Max Morinb51cf512018-02-19 12:49:49290Arguments bound with `base::BindOnce()` are always moved, if possible, to the
291target function.
292A function parameter that is passed by value and has a move constructor will be
293moved instead of copied.
294This makes it easy to use move-only types with `base::BindOnce()`.
295
296In contrast, arguments bound with `base::BindRepeating()` are only moved to the
297target function if the argument is bound with `base::Passed()`.
298
299**DANGER**:
300A `base::RepeatingCallback` can only be run once if arguments were bound with
301`base::Passed()`.
302For this reason, avoid `base::Passed()`.
303If you know a callback will only be called once, prefer to refactor code to
304work with `base::OnceCallback` instead.
305
306Avoid using `base::Passed()` with `base::BindOnce()`, as `std::move()` does the
307same thing and is more familiar.
tzik7c0c0cf12016-10-05 08:14:05308
309```cpp
310void Foo(std::unique_ptr<int>) {}
Max Morinb51cf512018-02-19 12:49:49311auto p = std::make_unique<int>(42);
tzik7c0c0cf12016-10-05 08:14:05312
313// |p| is moved into the internal storage of Bind(), and moved out to |Foo|.
Brett Wilson508162c2017-09-27 22:24:46314base::BindOnce(&Foo, std::move(p));
Max Morinb51cf512018-02-19 12:49:49315base::BindRepeating(&Foo, base::Passed(&p)); // Ok, but subtle.
316base::BindRepeating(&Foo, base::Passed(std::move(p))); // Ok, but subtle.
tzik7c0c0cf12016-10-05 08:14:05317```
318
tzika4313512016-09-06 06:51:12319## Quick reference for advanced binding
tzik703f1562016-09-02 07:36:55320
tzika4313512016-09-06 06:51:12321### Binding A Class Method With Weak Pointers
tzik703f1562016-09-02 07:36:55322
323```cpp
Brett Wilson508162c2017-09-27 22:24:46324base::Bind(&MyClass::Foo, GetWeakPtr());
tzika4313512016-09-06 06:51:12325```
tzik703f1562016-09-02 07:36:55326
327The callback will not be run if the object has already been destroyed.
Brett Wilson508162c2017-09-27 22:24:46328**DANGER**: weak pointers are not threadsafe, so don't use this when passing
329between threads!
330
331To make a weak pointer, you would typically create a
332`base::WeakPtrFactory<Foo>` member at the bottom (to ensure it's destroyed
333last) of class `Foo`, then call `weak_factory_.GetWeakPtr()`.
tzik703f1562016-09-02 07:36:55334
tzika4313512016-09-06 06:51:12335### Binding A Class Method With Manual Lifetime Management
tzik703f1562016-09-02 07:36:55336
337```cpp
Brett Wilson508162c2017-09-27 22:24:46338base::Bind(&MyClass::Foo, base::Unretained(this));
tzik703f1562016-09-02 07:36:55339```
340
tzika4313512016-09-06 06:51:12341This disables all lifetime management on the object. You're responsible for
342making sure the object is alive at the time of the call. You break it, you own
343it!
tzik703f1562016-09-02 07:36:55344
tzika4313512016-09-06 06:51:12345### Binding A Class Method And Having The Callback Own The Class
tzik703f1562016-09-02 07:36:55346
347```cpp
348MyClass* myclass = new MyClass;
Brett Wilson508162c2017-09-27 22:24:46349base::Bind(&MyClass::Foo, base::Owned(myclass));
tzik703f1562016-09-02 07:36:55350```
351
tzika4313512016-09-06 06:51:12352The object will be deleted when the callback is destroyed, even if it's not run
353(like if you post a task during shutdown). Potentially useful for "fire and
354forget" cases.
tzik703f1562016-09-02 07:36:55355
tzik7c0c0cf12016-10-05 08:14:05356Smart pointers (e.g. `std::unique_ptr<>`) are also supported as the receiver.
357
358```cpp
359std::unique_ptr<MyClass> myclass(new MyClass);
Brett Wilson508162c2017-09-27 22:24:46360base::Bind(&MyClass::Foo, std::move(myclass));
tzik7c0c0cf12016-10-05 08:14:05361```
362
tzika4313512016-09-06 06:51:12363### Ignoring Return Values
tzik703f1562016-09-02 07:36:55364
tzika4313512016-09-06 06:51:12365Sometimes you want to call a function that returns a value in a callback that
366doesn't expect a return value.
tzik703f1562016-09-02 07:36:55367
368```cpp
369int DoSomething(int arg) { cout << arg << endl; }
Brett Wilson508162c2017-09-27 22:24:46370base::Callback<void(int)> cb =
371 base::Bind(IgnoreResult(&DoSomething));
tzik703f1562016-09-02 07:36:55372```
373
tzika4313512016-09-06 06:51:12374## Quick reference for binding parameters to Bind()
tzik703f1562016-09-02 07:36:55375
Brett Wilson508162c2017-09-27 22:24:46376Bound parameters are specified as arguments to `base::Bind()` and are passed to
377the function. A callback with no parameters or no unbound parameters is called
378a `base::Closure` (`base::Callback<void()>` and `base::Closure` are the same
379thing).
tzik703f1562016-09-02 07:36:55380
tzika4313512016-09-06 06:51:12381### Passing Parameters Owned By The Callback
tzik703f1562016-09-02 07:36:55382
383```cpp
384void Foo(int* arg) { cout << *arg << endl; }
385int* pn = new int(1);
Brett Wilson508162c2017-09-27 22:24:46386base::Closure foo_callback = base::Bind(&foo, base::Owned(pn));
tzik703f1562016-09-02 07:36:55387```
388
tzika4313512016-09-06 06:51:12389The parameter will be deleted when the callback is destroyed, even if it's not
390run (like if you post a task during shutdown).
tzik703f1562016-09-02 07:36:55391
tzika4313512016-09-06 06:51:12392### Passing Parameters As A unique_ptr
tzik703f1562016-09-02 07:36:55393
394```cpp
395void TakesOwnership(std::unique_ptr<Foo> arg) {}
Max Morinb51cf512018-02-19 12:49:49396auto f = std::make_unique<Foo>();
tzik703f1562016-09-02 07:36:55397// f becomes null during the following call.
Max Morinb51cf512018-02-19 12:49:49398base::OnceClosure cb = base::BindOnce(&TakesOwnership, std::move(f));
tzik703f1562016-09-02 07:36:55399```
400
tzika4313512016-09-06 06:51:12401Ownership of the parameter will be with the callback until the callback is run,
402and then ownership is passed to the callback function. This means the callback
403can only be run once. If the callback is never run, it will delete the object
404when it's destroyed.
tzik703f1562016-09-02 07:36:55405
tzika4313512016-09-06 06:51:12406### Passing Parameters As A scoped_refptr
tzik703f1562016-09-02 07:36:55407
408```cpp
409void TakesOneRef(scoped_refptr<Foo> arg) {}
tzik7c0c0cf12016-10-05 08:14:05410scoped_refptr<Foo> f(new Foo);
Brett Wilson508162c2017-09-27 22:24:46411base::Closure cb = base::Bind(&TakesOneRef, f);
tzik703f1562016-09-02 07:36:55412```
413
tzika4313512016-09-06 06:51:12414This should "just work." The closure will take a reference as long as it is
415alive, and another reference will be taken for the called function.
tzik703f1562016-09-02 07:36:55416
tzik7c0c0cf12016-10-05 08:14:05417```cpp
418void DontTakeRef(Foo* arg) {}
419scoped_refptr<Foo> f(new Foo);
Brett Wilson508162c2017-09-27 22:24:46420base::Closure cb = base::Bind(&DontTakeRef, base::RetainedRef(f));
tzik7c0c0cf12016-10-05 08:14:05421```
422
Brett Wilson508162c2017-09-27 22:24:46423`base::RetainedRef` holds a reference to the object and passes a raw pointer to
tzik7c0c0cf12016-10-05 08:14:05424the object when the Callback is run.
425
tzika4313512016-09-06 06:51:12426### Passing Parameters By Reference
tzik703f1562016-09-02 07:36:55427
Brett Wilson508162c2017-09-27 22:24:46428Const references are *copied* unless `base::ConstRef` is used. Example:
tzik703f1562016-09-02 07:36:55429
430```cpp
431void foo(const int& arg) { printf("%d %p\n", arg, &arg); }
432int n = 1;
Brett Wilson508162c2017-09-27 22:24:46433base::Closure has_copy = base::Bind(&foo, n);
434base::Closure has_ref = base::Bind(&foo, base::ConstRef(n));
tzik703f1562016-09-02 07:36:55435n = 2;
436foo(n); // Prints "2 0xaaaaaaaaaaaa"
437has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb"
438has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa"
439```
440
tzika4313512016-09-06 06:51:12441Normally parameters are copied in the closure.
Brett Wilson508162c2017-09-27 22:24:46442**DANGER**: `base::ConstRef` stores a const reference instead, referencing the
tzik7c0c0cf12016-10-05 08:14:05443original parameter. This means that you must ensure the object outlives the
444callback!
tzik703f1562016-09-02 07:36:55445
tzika4313512016-09-06 06:51:12446## Implementation notes
tzik703f1562016-09-02 07:36:55447
tzika4313512016-09-06 06:51:12448### Where Is This Design From:
tzik703f1562016-09-02 07:36:55449
Brett Wilson508162c2017-09-27 22:24:46450The design of `base::Callback` and `base::Bind` is heavily influenced by C++'s
451`tr1::function` / `tr1::bind`, and by the "Google Callback" system used inside
452Google.
tzik703f1562016-09-02 07:36:55453
tzik7c0c0cf12016-10-05 08:14:05454### Customizing the behavior
455
Brett Wilson508162c2017-09-27 22:24:46456There are several injection points that controls binding behavior from outside
457of its implementation.
tzik7c0c0cf12016-10-05 08:14:05458
459```cpp
Brett Wilson508162c2017-09-27 22:24:46460namespace base {
461
tzik7c0c0cf12016-10-05 08:14:05462template <typename Receiver>
463struct IsWeakReceiver {
464 static constexpr bool value = false;
465};
466
467template <typename Obj>
468struct UnwrapTraits {
469 template <typename T>
470 T&& Unwrap(T&& obj) {
471 return std::forward<T>(obj);
472 }
473};
Brett Wilson508162c2017-09-27 22:24:46474
475} // namespace base
tzik7c0c0cf12016-10-05 08:14:05476```
477
Brett Wilson508162c2017-09-27 22:24:46478If `base::IsWeakReceiver<Receiver>::value` is true on a receiver of a method,
479`base::Bind` checks if the receiver is evaluated to true and cancels the invocation
480if it's evaluated to false. You can specialize `base::IsWeakReceiver` to make
481an external smart pointer as a weak pointer.
tzik7c0c0cf12016-10-05 08:14:05482
Brett Wilson508162c2017-09-27 22:24:46483`base::UnwrapTraits<BoundObject>::Unwrap()` is called for each bound arguments
484right before `base::Callback` calls the target function. You can specialize
485this to define an argument wrapper such as `base::Unretained`,
486`base::ConstRef`, `base::Owned`, `base::RetainedRef` and `base::Passed`.
tzik7c0c0cf12016-10-05 08:14:05487
tzika4313512016-09-06 06:51:12488### How The Implementation Works:
tzik703f1562016-09-02 07:36:55489
490There are three main components to the system:
Brett Wilson508162c2017-09-27 22:24:46491 1) The `base::Callback<>` classes.
492 2) The `base::Bind()` functions.
493 3) The arguments wrappers (e.g., `base::Unretained()` and `base::ConstRef()`).
tzik703f1562016-09-02 07:36:55494
Brett Wilson508162c2017-09-27 22:24:46495The Callback classes represent a generic function pointer. Internally, it
496stores a refcounted piece of state that represents the target function and all
497its bound parameters. The `base::Callback` constructor takes a
498`base::BindStateBase*`, which is upcasted from a `base::BindState<>`. In the
499context of the constructor, the static type of this `base::BindState<>` pointer
500uniquely identifies the function it is representing, all its bound parameters,
501and a `Run()` method that is capable of invoking the target.
tzik703f1562016-09-02 07:36:55502
Brett Wilson508162c2017-09-27 22:24:46503`base::Bind()` creates the `base::BindState<>` that has the full static type,
504and erases the target function type as well as the types of the bound
505parameters. It does this by storing a pointer to the specific `Run()` function,
506and upcasting the state of `base::BindState<>*` to a `base::BindStateBase*`.
507This is safe as long as this `BindStateBase` pointer is only used with the
508stored `Run()` pointer.
tzik703f1562016-09-02 07:36:55509
Brett Wilson508162c2017-09-27 22:24:46510To `base::BindState<>` objects are created inside the `base::Bind()` functions.
tzik703f1562016-09-02 07:36:55511These functions, along with a set of internal templates, are responsible for
512
513 - Unwrapping the function signature into return type, and parameters
514 - Determining the number of parameters that are bound
515 - Creating the BindState storing the bound parameters
516 - Performing compile-time asserts to avoid error-prone behavior
517 - Returning an `Callback<>` with an arity matching the number of unbound
518 parameters and that knows the correct refcounting semantics for the
519 target object if we are binding a method.
520
Brett Wilson508162c2017-09-27 22:24:46521The `base::Bind` functions do the above using type-inference and variadic
522templates.
tzik703f1562016-09-02 07:36:55523
Brett Wilson508162c2017-09-27 22:24:46524By default `base::Bind()` will store copies of all bound parameters, and
525attempt to refcount a target object if the function being bound is a class
526method. These copies are created even if the function takes parameters as const
tzik703f1562016-09-02 07:36:55527references. (Binding to non-const references is forbidden, see bind.h.)
528
tzika4313512016-09-06 06:51:12529To change this behavior, we introduce a set of argument wrappers (e.g.,
Brett Wilson508162c2017-09-27 22:24:46530`base::Unretained()`, and `base::ConstRef()`). These are simple container
531templates that are passed by value, and wrap a pointer to argument. See the
532file-level comment in base/bind_helpers.h for more info.
tzik703f1562016-09-02 07:36:55533
tzik7c0c0cf12016-10-05 08:14:05534These types are passed to the `Unwrap()` functions to modify the behavior of
Brett Wilson508162c2017-09-27 22:24:46535`base::Bind()`. The `Unwrap()` functions change behavior by doing partial
tzik7c0c0cf12016-10-05 08:14:05536specialization based on whether or not a parameter is a wrapper type.
tzik703f1562016-09-02 07:36:55537
Brett Wilson508162c2017-09-27 22:24:46538`base::ConstRef()` is similar to `tr1::cref`. `base::Unretained()` is specific
539to Chromium.
tzik703f1562016-09-02 07:36:55540
tzika4313512016-09-06 06:51:12541### Missing Functionality
tzik703f1562016-09-02 07:36:55542 - Binding arrays to functions that take a non-const pointer.
543 Example:
544```cpp
545void Foo(const char* ptr);
546void Bar(char* ptr);
Brett Wilson508162c2017-09-27 22:24:46547base::Bind(&Foo, "test");
548base::Bind(&Bar, "test"); // This fails because ptr is not const.
tzik703f1562016-09-02 07:36:55549```
Gayane Petrosyan7f716982018-03-09 15:17:34550 - In case of partial binding of parameters a possibility of having unbound
551 parameters before bound parameters. Example:
552```cpp
553void Foo(int x, bool y);
554base::Bind(&Foo, _1, false); // _1 is a placeholder.
555```
tzik703f1562016-09-02 07:36:55556
Brett Wilson508162c2017-09-27 22:24:46557If you are thinking of forward declaring `base::Callback` in your own header
558file, please include "base/callback_forward.h" instead.