1# Callback<> and Bind() 2 3[TOC] 4 5## Introduction 6 7The 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. 10 11Partial 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. 16 17A 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. 21 22### OnceCallback<> And RepeatingCallback<> 23 24`base::OnceCallback<>` and `base::RepeatingCallback<>` are next gen callback 25classes, which are under development. 26 27`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. 33 34`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. 39 40The 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. 45 46`base::RepeatingCallback<>` is convertible to `base::OnceCallback<>` by the 47implicit conversion. 48 49### Memory Management And Passing 50 51Pass `base::{Once,Repeating}Callback` objects by value if ownership is 52transferred; otherwise, pass it by const-reference. 53 54```cpp 55// |Foo| just refers to |cb| but doesn't store it nor consume it. 56bool Foo(const base::OnceCallback<void(int)>& cb) { 57 return cb.is_null(); 58} 59 60// |Bar| takes the ownership of |cb| and stores |cb| into |g_cb|. 61base::RepeatingCallback<void(int)> g_cb; 62void Bar(base::RepeatingCallback<void(int)> cb) { 63 g_cb = std::move(cb); 64} 65 66// |Baz| takes the ownership of |cb| and consumes |cb| by Run(). 67void Baz(base::OnceCallback<void(int)> cb) { 68 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|. 73void Qux(base::RepeatingCallback<void(int)> cb) { 74 PostTask(FROM_HERE, base::BindOnce(cb, 42)); 75 PostTask(FROM_HERE, base::BindOnce(std::move(cb), 43)); 76} 77``` 78 79When 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 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::{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. 86 87### 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 166If the second callback does not want to receive a value from the first callback, 167you may use `base::IgnoreResult` to drop the return value in between running the 168two. 169 170```cpp 171// Returns an integer. 172base::RepeatingCallback<int()> first = base::BindRepeating([](){ return 5; }); 173// Does not want to receive an integer. 174base::RepeatingClosure second = base::BindRepeating([](){}); 175 176// This will not compile, because |second| can not receive the return value from 177// |first|. 178// first.Then(second).Run(); 179 180// We can drop the result from |first| before running second. 181base::BindRepeating(base::IgnoreResult(first)).Then(second).Run(); 182// This will effectively create a callback that when Run() will call 183// `first(); second();` instead of `second(first());`. 184``` 185 186Note that the return value from |first| will be lost in the above example, and 187would be destroyed before |second| is run. If you want the return value from 188|first| to be preserved and ultimately returned after running both |first| and 189|second|, then you would need a primitive such as the `base::PassThrough<T>()` 190helper in the [base::PassThrough CL](https://chromium-review.googlesource.com/c/chromium/src/+/2493243). 191If this would be helpful for you, please let danakj@chromium.org know or ping 192the CL. 193 194### Chaining callbacks across different task runners 195 196```cpp 197// The task runner for a different thread. 198scoped_refptr<base::SequencedTaskRunner> other_task_runner = ...; 199 200// A function to compute some interesting result, except it can only be run 201// safely from `other_task_runner` and not the current thread. 202int ComputeResult(); 203 204base::OnceCallback<int()> compute_result_cb = base::BindOnce(&ComputeResult); 205 206// Task runner for the current thread. 207scoped_refptr<base::SequencedTaskRunner> current_task_runner = 208 base::SequencedTaskRunnerHandle::Get(); 209 210// A function to accept the result, except it can only be run safely from the 211// current thread. 212void ProvideResult(int result); 213 214base::OnceCallback<void(int)> provide_result_cb = 215 base::BindOnce(&ProvideResult); 216``` 217 218Using `Then()` to join `compute_result_cb` and `provide_result_cb` directly 219would be inappropriate. `ComputeResult()` and `ProvideResult()` would run on the 220same thread which isn't safe. However, `base::BindPostTask()` can be used to 221ensure `provide_result_cb` will run on `current_task_runner`. 222 223```cpp 224// The following two statements post a task to `other_task_runner` to run 225// `task`. This will invoke ComputeResult() on a different thread to get the 226// result value then post a task back to `current_task_runner` to invoke 227// ProvideResult() with the result. 228OnceClosure task = 229 std::move(compute_result_cb) 230 .Then(base::BindPostTask(current_task_runner, 231 std::move(provide_result_cb))); 232other_task_runner->PostTask(FROM_HERE, std::move(task)); 233``` 234 235## Quick reference for basic stuff 236 237### Binding A Bare Function 238 239```cpp 240int Return5() { return 5; } 241base::OnceCallback<int()> func_cb = base::BindOnce(&Return5); 242LOG(INFO) << std::move(func_cb).Run(); // Prints 5. 243``` 244 245```cpp 246int Return5() { return 5; } 247base::RepeatingCallback<int()> func_cb = base::BindRepeating(&Return5); 248LOG(INFO) << func_cb.Run(); // Prints 5. 249``` 250 251### Binding A Captureless Lambda 252 253```cpp 254base::Callback<int()> lambda_cb = base::Bind([] { return 4; }); 255LOG(INFO) << lambda_cb.Run(); // Print 4. 256 257base::OnceCallback<int()> lambda_cb2 = base::BindOnce([] { return 3; }); 258LOG(INFO) << std::move(lambda_cb2).Run(); // Print 3. 259 260base::OnceCallback<int()> lambda_cb3 = base::BindOnce([] { return 2; }); 261base::OnceCallback<int(base::OnceCallback<int()>)> lambda_cb4 = 262 base::BindOnce( 263 [](base::OnceCallback<int()> callback) { 264 return std::move(callback).Run(); }, 265 std::move(lambda_cb3)); 266LOG(INFO) << std::move(lambda_cb4).Run(); // Print 2. 267 268``` 269 270### Binding A Capturing Lambda (In Tests) 271 272When writing tests, it is often useful to capture arguments that need to be 273modified in a callback. 274 275``` cpp 276#include "base/test/bind.h" 277 278int i = 2; 279base::Callback<void()> lambda_cb = base::BindLambdaForTesting([&]() { i++; }); 280lambda_cb.Run(); 281LOG(INFO) << i; // Print 3; 282``` 283 284### Binding A Class Method 285 286The first argument to bind is the member function to call, the second is the 287object on which to call it. 288 289```cpp 290class Ref : public base::RefCountedThreadSafe<Ref> { 291 public: 292 int Foo() { return 3; } 293}; 294scoped_refptr<Ref> ref = new Ref(); 295base::Callback<void()> ref_cb = base::Bind(&Ref::Foo, ref); 296LOG(INFO) << ref_cb.Run(); // Prints out 3. 297``` 298 299By default the object must support RefCounted or you will get a compiler 300error. If you're passing between threads, be sure it's RefCountedThreadSafe! See 301"Advanced binding of member functions" below if you don't want to use reference 302counting. 303 304### Running A Callback 305 306Callbacks can be run with their `Run` method, which has the same signature as 307the template argument to the callback. Note that `base::OnceCallback::Run` 308consumes the callback object and can only be invoked on a callback rvalue. 309 310```cpp 311void DoSomething(const base::Callback<void(int, std::string)>& callback) { 312 callback.Run(5, "hello"); 313} 314 315void DoSomethingOther(base::OnceCallback<void(int, std::string)> callback) { 316 std::move(callback).Run(5, "hello"); 317} 318``` 319 320RepeatingCallbacks can be run more than once (they don't get deleted or marked 321when run). However, this precludes using `base::Passed` (see below). 322 323```cpp 324void DoSomething(const base::RepeatingCallback<double(double)>& callback) { 325 double myresult = callback.Run(3.14159); 326 myresult += callback.Run(2.71828); 327} 328``` 329 330If running a callback could result in its own destruction (e.g., if the callback 331recipient deletes the object the callback is a member of), the callback should 332be moved before it can be safely invoked. (Note that this is only an issue for 333RepeatingCallbacks, because a OnceCallback always has to be moved for 334execution.) 335 336```cpp 337void Foo::RunCallback() { 338 std::move(&foo_deleter_callback_).Run(); 339} 340``` 341 342### Creating a Callback That Does Nothing 343 344Sometimes you need a callback that does nothing when run (e.g. test code that 345doesn't care to be notified about certain types of events). It may be tempting 346to pass a default-constructed callback of the right type: 347 348```cpp 349using MyCallback = base::OnceCallback<void(bool arg)>; 350void MyFunction(MyCallback callback) { 351 std::move(callback).Run(true); // Uh oh... 352} 353... 354MyFunction(MyCallback()); // ...this will crash when Run()! 355``` 356 357Default-constructed callbacks are null, and thus cannot be Run(). Instead, use 358`base::DoNothing()`: 359 360```cpp 361... 362MyFunction(base::DoNothing()); // Can be Run(), will no-op 363``` 364 365`base::DoNothing()` can be passed for any OnceCallback or RepeatingCallback that 366returns void. 367 368Implementation-wise, `base::DoNothing()` is actually a functor which produces a 369callback from `operator()`. This makes it unusable when trying to bind other 370arguments to it. Normally, the only reason to bind arguments to DoNothing() is 371to manage object lifetimes, and in these cases, you should strive to use idioms 372like DeleteSoon(), ReleaseSoon(), or RefCountedDeleteOnSequence instead. If you 373truly need to bind an argument to DoNothing(), or if you need to explicitly 374create a callback object (because implicit conversion through operator()() won't 375compile), you can instantiate directly: 376 377```cpp 378// Binds |foo_ptr| to a no-op OnceCallback takes a scoped_refptr<Foo>. 379// ANTIPATTERN WARNING: This should likely be changed to ReleaseSoon()! 380base::Bind(base::DoNothing::Once<scoped_refptr<Foo>>(), foo_ptr); 381``` 382 383### Passing Unbound Input Parameters 384 385Unbound parameters are specified at the time a callback is `Run()`. They are 386specified in the `base::Callback` template type: 387 388```cpp 389void MyFunc(int i, const std::string& str) {} 390base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc); 391cb.Run(23, "hello, world"); 392``` 393 394### Passing Bound Input Parameters 395 396Bound parameters are specified when you create the callback as arguments to 397`base::Bind()`. They will be passed to the function and the `Run()`ner of the 398callback doesn't see those values or even know that the function it's calling. 399 400```cpp 401void MyFunc(int i, const std::string& str) {} 402base::Callback<void()> cb = base::Bind(&MyFunc, 23, "hello world"); 403cb.Run(); 404``` 405 406A callback with no unbound input parameters (`base::Callback<void()>`) is 407called a `base::Closure`. So we could have also written: 408 409```cpp 410base::Closure cb = base::Bind(&MyFunc, 23, "hello world"); 411``` 412 413When calling member functions, bound parameters just go after the object 414pointer. 415 416```cpp 417base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world"); 418``` 419 420### Partial Binding Of Parameters 421 422You can specify some parameters when you create the callback, and specify the 423rest when you execute the callback. 424 425When calling a function bound parameters are first, followed by unbound 426parameters. 427 428```cpp 429void ReadIntFromFile(const std::string& filename, 430 base::OnceCallback<void(int)> on_read); 431 432void DisplayIntWithPrefix(const std::string& prefix, int result) { 433 LOG(INFO) << prefix << result; 434} 435 436void AnotherFunc(const std::string& file) { 437 ReadIntFromFile(file, base::BindOnce(&DisplayIntWithPrefix, "MyPrefix: ")); 438}; 439``` 440 441This technique is known as [partial 442application](http://en.wikipedia.org/wiki/Partial_application). It should be 443used in lieu of creating an adapter class that holds the bound arguments. Notice 444also that the `"MyPrefix: "` argument is actually a `const char*`, while 445`DisplayIntWithPrefix` actually wants a `const std::string&`. Like normal 446function dispatch, `base::Bind`, will coerce parameter types if possible. 447 448### Avoiding Copies With Callback Parameters 449 450A parameter of `base::BindRepeating()` or `base::BindOnce()` is moved into its 451internal storage if it is passed as a rvalue. 452 453```cpp 454std::vector<int> v = {1, 2, 3}; 455// |v| is moved into the internal storage without copy. 456base::Bind(&Foo, std::move(v)); 457``` 458 459```cpp 460// The vector is moved into the internal storage without copy. 461base::Bind(&Foo, std::vector<int>({1, 2, 3})); 462``` 463 464Arguments bound with `base::BindOnce()` are always moved, if possible, to the 465target function. 466A function parameter that is passed by value and has a move constructor will be 467moved instead of copied. 468This makes it easy to use move-only types with `base::BindOnce()`. 469 470In contrast, arguments bound with `base::BindRepeating()` are only moved to the 471target function if the argument is bound with `base::Passed()`. 472 473**DANGER**: 474A `base::RepeatingCallback` can only be run once if arguments were bound with 475`base::Passed()`. 476For this reason, avoid `base::Passed()`. 477If you know a callback will only be called once, prefer to refactor code to 478work with `base::OnceCallback` instead. 479 480Avoid using `base::Passed()` with `base::BindOnce()`, as `std::move()` does the 481same thing and is more familiar. 482 483```cpp 484void Foo(std::unique_ptr<int>) {} 485auto p = std::make_unique<int>(42); 486 487// |p| is moved into the internal storage of Bind(), and moved out to |Foo|. 488base::BindOnce(&Foo, std::move(p)); 489base::BindRepeating(&Foo, base::Passed(&p)); // Ok, but subtle. 490base::BindRepeating(&Foo, base::Passed(std::move(p))); // Ok, but subtle. 491``` 492 493## Quick reference for advanced binding 494 495### Binding A Class Method With Weak Pointers 496 497If `MyClass` has a `base::WeakPtr<MyClass> weak_this_` member (see below) 498then a class method can be bound with: 499 500```cpp 501base::Bind(&MyClass::Foo, weak_this_); 502``` 503 504The callback will not be run if the object has already been destroyed. 505 506Note that class method callbacks bound to `base::WeakPtr`s may only be 507run on the same sequence on which the object will be destroyed, since otherwise 508execution of the callback might race with the object's deletion. 509 510To use `base::WeakPtr` with `base::Bind()`, `MyClass` will typically look like: 511 512```cpp 513class MyClass { 514public: 515 MyClass() { 516 weak_this_ = weak_factory_.GetWeakPtr(); 517 } 518private: 519 base::WeakPtr<MyClass> weak_this_; 520 // MyClass member variables go here. 521 base::WeakPtrFactory<MyClass> weak_factory_{this}; 522}; 523``` 524 525`weak_factory_` is the last member variable in `MyClass` so that it is 526destroyed first. This ensures that if any class methods bound to `weak_this_` 527are `Run()` during teardown, then they will not actually be executed. 528 529If `MyClass` only ever `base::Bind()`s and executes callbacks on the same 530sequence, then it is generally safe to call `weak_factory_.GetWeakPtr()` at the 531`base::Bind()` call, rather than taking a separate `weak_this_` during 532construction. 533 534### Binding A Class Method With Manual Lifetime Management 535 536```cpp 537base::Bind(&MyClass::Foo, base::Unretained(this)); 538``` 539 540This disables all lifetime management on the object. You're responsible for 541making sure the object is alive at the time of the call. You break it, you own 542it! 543 544### Binding A Class Method And Having The Callback Own The Class 545 546```cpp 547MyClass* myclass = new MyClass; 548base::Bind(&MyClass::Foo, base::Owned(myclass)); 549``` 550 551The object will be deleted when the callback is destroyed, even if it's not run 552(like if you post a task during shutdown). Potentially useful for "fire and 553forget" cases. 554 555Smart pointers (e.g. `std::unique_ptr<>`) are also supported as the receiver. 556 557```cpp 558std::unique_ptr<MyClass> myclass(new MyClass); 559base::Bind(&MyClass::Foo, std::move(myclass)); 560``` 561 562### Ignoring Return Values 563 564Sometimes you want to call a function that returns a value in a callback that 565doesn't expect a return value. 566 567```cpp 568int DoSomething(int arg) { cout << arg << endl; } 569base::RepeatingCallback<void(int)> cb = 570 base::BindRepeating(IgnoreResult(&DoSomething)); 571``` 572 573Similarly, you may want to use an existing callback that returns a value in a 574place that expects a void return type. 575 576```cpp 577base::RepeatingCallback<int()> cb = base::BindRepeating([](){ return 5; }); 578base::RepeatingClosure void_cb = base::BindRepeating(base::IgnoreResult(cb)); 579``` 580 581## Quick reference for binding parameters to Bind() 582 583Bound parameters are specified as arguments to `base::Bind()` and are passed to 584the function. A callback with no parameters or no unbound parameters is called 585a `base::Closure` (`base::Callback<void()>` and `base::Closure` are the same 586thing). 587 588### Passing Parameters Owned By The Callback 589 590```cpp 591void Foo(int* arg) { cout << *arg << endl; } 592int* pn = new int(1); 593base::Closure foo_callback = base::Bind(&foo, base::Owned(pn)); 594``` 595 596The parameter will be deleted when the callback is destroyed, even if it's not 597run (like if you post a task during shutdown). 598 599### Passing Parameters As A unique_ptr 600 601```cpp 602void TakesOwnership(std::unique_ptr<Foo> arg) {} 603auto f = std::make_unique<Foo>(); 604// f becomes null during the following call. 605base::OnceClosure cb = base::BindOnce(&TakesOwnership, std::move(f)); 606``` 607 608Ownership of the parameter will be with the callback until the callback is run, 609and then ownership is passed to the callback function. This means the callback 610can only be run once. If the callback is never run, it will delete the object 611when it's destroyed. 612 613### Passing Parameters As A scoped_refptr 614 615```cpp 616void TakesOneRef(scoped_refptr<Foo> arg) {} 617scoped_refptr<Foo> f(new Foo); 618base::Closure cb = base::Bind(&TakesOneRef, f); 619``` 620 621This should "just work." The closure will take a reference as long as it is 622alive, and another reference will be taken for the called function. 623 624```cpp 625void DontTakeRef(Foo* arg) {} 626scoped_refptr<Foo> f(new Foo); 627base::Closure cb = base::Bind(&DontTakeRef, base::RetainedRef(f)); 628``` 629 630`base::RetainedRef` holds a reference to the object and passes a raw pointer to 631the object when the Callback is run. 632 633### Passing Parameters By Reference 634 635References are *copied* unless `std::ref` or `std::cref` is used. Example: 636 637```cpp 638void foo(const int& arg) { printf("%d %p\n", arg, &arg); } 639int n = 1; 640base::Closure has_copy = base::Bind(&foo, n); 641base::Closure has_ref = base::Bind(&foo, std::cref(n)); 642n = 2; 643foo(n); // Prints "2 0xaaaaaaaaaaaa" 644has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb" 645has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa" 646``` 647 648Normally parameters are copied in the closure. 649**DANGER**: `std::ref` and `std::cref` store a (const) reference instead, 650referencing the original parameter. This means that you must ensure the object 651outlives the callback! 652 653## Implementation notes 654 655### Where Is This Design From: 656 657The design of `base::Callback` and `base::Bind` is heavily influenced by C++'s 658`tr1::function` / `tr1::bind`, and by the "Google Callback" system used inside 659Google. 660 661### Customizing the behavior 662 663There are several injection points that controls binding behavior from outside 664of its implementation. 665 666```cpp 667namespace base { 668 669template <typename Receiver> 670struct IsWeakReceiver { 671 static constexpr bool value = false; 672}; 673 674template <typename Obj> 675struct UnwrapTraits { 676 template <typename T> 677 T&& Unwrap(T&& obj) { 678 return std::forward<T>(obj); 679 } 680}; 681 682} // namespace base 683``` 684 685If `base::IsWeakReceiver<Receiver>::value` is true on a receiver of a method, 686`base::Bind` checks if the receiver is evaluated to true and cancels the invocation 687if it's evaluated to false. You can specialize `base::IsWeakReceiver` to make 688an external smart pointer as a weak pointer. 689 690`base::UnwrapTraits<BoundObject>::Unwrap()` is called for each bound arguments 691right before `base::Callback` calls the target function. You can specialize this 692to define an argument wrapper such as `base::Unretained`, `base::Owned`, 693`base::RetainedRef` and `base::Passed`. 694 695### How The Implementation Works: 696 697There are three main components to the system: 698 1) The `base::Callback<>` classes. 699 2) The `base::Bind()` functions. 700 3) The arguments wrappers (e.g., `base::Unretained()` and `base::Owned()`). 701 702The Callback classes represent a generic function pointer. Internally, it 703stores a refcounted piece of state that represents the target function and all 704its bound parameters. The `base::Callback` constructor takes a 705`base::BindStateBase*`, which is upcasted from a `base::BindState<>`. In the 706context of the constructor, the static type of this `base::BindState<>` pointer 707uniquely identifies the function it is representing, all its bound parameters, 708and a `Run()` method that is capable of invoking the target. 709 710`base::Bind()` creates the `base::BindState<>` that has the full static type, 711and erases the target function type as well as the types of the bound 712parameters. It does this by storing a pointer to the specific `Run()` function, 713and upcasting the state of `base::BindState<>*` to a `base::BindStateBase*`. 714This is safe as long as this `BindStateBase` pointer is only used with the 715stored `Run()` pointer. 716 717To `base::BindState<>` objects are created inside the `base::Bind()` functions. 718These functions, along with a set of internal templates, are responsible for 719 720 - Unwrapping the function signature into return type, and parameters 721 - Determining the number of parameters that are bound 722 - Creating the BindState storing the bound parameters 723 - Performing compile-time asserts to avoid error-prone behavior 724 - Returning a `Callback<>` with an arity matching the number of unbound 725 parameters and that knows the correct refcounting semantics for the 726 target object if we are binding a method. 727 728The `base::Bind` functions do the above using type-inference and variadic 729templates. 730 731By default `base::Bind()` will store copies of all bound parameters, and 732attempt to refcount a target object if the function being bound is a class 733method. These copies are created even if the function takes parameters as const 734references. (Binding to non-const references is forbidden, see bind.h.) 735 736To change this behavior, we introduce a set of argument wrappers (e.g., 737`base::Unretained()`). These are simple container templates that are passed by 738value, and wrap a pointer to argument. Each helper has a comment describing it 739in base/bind.h. 740 741These types are passed to the `Unwrap()` functions to modify the behavior of 742`base::Bind()`. The `Unwrap()` functions change behavior by doing partial 743specialization based on whether or not a parameter is a wrapper type. 744 745`base::Unretained()` is specific to Chromium. 746 747### Missing Functionality 748 - Binding arrays to functions that take a non-const pointer. 749 Example: 750```cpp 751void Foo(const char* ptr); 752void Bar(char* ptr); 753base::Bind(&Foo, "test"); 754base::Bind(&Bar, "test"); // This fails because ptr is not const. 755``` 756 - In case of partial binding of parameters a possibility of having unbound 757 parameters before bound parameters. Example: 758```cpp 759void Foo(int x, bool y); 760base::Bind(&Foo, _1, false); // _1 is a placeholder. 761``` 762 763If you are thinking of forward declaring `base::Callback` in your own header 764file, please include "base/callback_forward.h" instead. 765