tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 1 | # Callback<> and Bind() |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 2 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 3 | ## Introduction |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 4 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 5 | The templated `base::Callback<>` class is a generalized function object. |
| 6 | Together with the `base::Bind()` function in base/bind.h, they provide a |
| 7 | type-safe method for performing partial application of functions. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 8 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 9 | Partial application (or "currying") is the process of binding a subset of a |
| 10 | function's arguments to produce another function that takes fewer arguments. |
| 11 | This can be used to pass around a unit of delayed execution, much like lexical |
| 12 | closures are used in other languages. For example, it is used in Chromium code |
| 13 | to schedule tasks on different MessageLoops. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 14 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 15 | A callback with no unbound input parameters (`base::Callback<void()>`) is |
| 16 | called a `base::Closure`. Note that this is NOT the same as what other |
| 17 | languages refer to as a closure -- it does not retain a reference to its |
| 18 | enclosing environment. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 19 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 20 | ### OnceCallback<> And RepeatingCallback<> |
| 21 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 22 | `base::OnceCallback<>` and `base::RepeatingCallback<>` are next gen callback |
| 23 | classes, which are under development. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 24 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 25 | `base::OnceCallback<>` is created by `base::BindOnce()`. This is a callback |
| 26 | variant that is a move-only type and can be run only once. This moves out bound |
| 27 | parameters from its internal storage to the bound function by default, so it's |
| 28 | easier to use with movable types. This should be the preferred callback type: |
| 29 | since the lifetime of the callback is clear, it's simpler to reason about when |
| 30 | a callback that is passed between threads is destroyed. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 31 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 32 | `base::RepeatingCallback<>` is created by `base::BindRepeating()`. This is a |
| 33 | callback variant that is copyable that can be run multiple times. It uses |
| 34 | internal ref-counting to make copies cheap. However, since ownership is shared, |
| 35 | it is harder to reason about when the callback and the bound state are |
| 36 | destroyed, especially when the callback is passed between threads. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 37 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 38 | The legacy `base::Callback<>` is currently aliased to |
| 39 | `base::RepeatingCallback<>`. In new code, prefer `base::OnceCallback<>` where |
| 40 | possible, and use `base::RepeatingCallback<>` otherwise. Once the migration is |
| 41 | complete, the type alias will be removed and `base::OnceCallback<>` will be renamed |
| 42 | to `base::Callback<>` to emphasize that it should be preferred. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 43 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 44 | `base::RepeatingCallback<>` is convertible to `base::OnceCallback<>` by the |
| 45 | implicit conversion. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 46 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 47 | ### Memory Management And Passing |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 48 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 49 | Pass `base::Callback` objects by value if ownership is transferred; otherwise, |
| 50 | pass it by const-reference. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 51 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 52 | ```cpp |
| 53 | // |Foo| just refers to |cb| but doesn't store it nor consume it. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 54 | bool Foo(const base::OnceCallback<void(int)>& cb) { |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 55 | return cb.is_null(); |
| 56 | } |
| 57 | |
| 58 | // |Bar| takes the ownership of |cb| and stores |cb| into |g_cb|. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 59 | base::OnceCallback<void(int)> g_cb; |
| 60 | void Bar(base::OnceCallback<void(int)> cb) { |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 61 | g_cb = std::move(cb); |
| 62 | } |
| 63 | |
| 64 | // |Baz| takes the ownership of |cb| and consumes |cb| by Run(). |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 65 | void Baz(base::OnceCallback<void(int)> cb) { |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 66 | 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 Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 71 | void Qux(base::OnceCallback<void(int)> cb) { |
michaelpg | 126f704d1 | 2017-03-14 23:22:53 | [diff] [blame] | 72 | PostTask(FROM_HERE, |
tzik | 298f67a | 2017-04-24 06:14:13 | [diff] [blame] | 73 | base::BindOnce(std::move(cb), 42)); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 74 | } |
| 75 | ``` |
| 76 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 77 | When 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 |
| 79 | object directly. You may see a compile error when the function requires the |
| 80 | exclusive ownership, and you didn't pass the callback by move. Note that the |
| 81 | moved-from `base::Callback` becomes null, as if its `Reset()` method had been |
| 82 | called, and its `is_null()` method will return true. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 83 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 84 | ## Quick reference for basic stuff |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 85 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 86 | ### Binding A Bare Function |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 87 | |
| 88 | ```cpp |
| 89 | int Return5() { return 5; } |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 90 | base::OnceCallback<int()> func_cb = base::BindOnce(&Return5); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 91 | LOG(INFO) << std::move(func_cb).Run(); // Prints 5. |
| 92 | ``` |
| 93 | |
| 94 | ```cpp |
| 95 | int Return5() { return 5; } |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 96 | base::RepeatingCallback<int()> func_cb = base::BindRepeating(&Return5); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 97 | LOG(INFO) << func_cb.Run(); // Prints 5. |
| 98 | ``` |
| 99 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 100 | ### Binding A Captureless Lambda |
| 101 | |
| 102 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 103 | base::Callback<int()> lambda_cb = base::Bind([] { return 4; }); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 104 | LOG(INFO) << lambda_cb.Run(); // Print 4. |
| 105 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 106 | base::OnceCallback<int()> lambda_cb2 = base::BindOnce([] { return 3; }); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 107 | LOG(INFO) << std::move(lambda_cb2).Run(); // Print 3. |
| 108 | ``` |
| 109 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 110 | ### Binding A Class Method |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 111 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 112 | The first argument to bind is the member function to call, the second is the |
| 113 | object on which to call it. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 114 | |
| 115 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 116 | class Ref : public base::RefCountedThreadSafe<Ref> { |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 117 | public: |
| 118 | int Foo() { return 3; } |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 119 | }; |
| 120 | scoped_refptr<Ref> ref = new Ref(); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 121 | base::Callback<void()> ref_cb = base::Bind(&Ref::Foo, ref); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 122 | LOG(INFO) << ref_cb.Run(); // Prints out 3. |
| 123 | ``` |
| 124 | |
| 125 | By default the object must support RefCounted or you will get a compiler |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 126 | error. 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 |
| 128 | counting. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 129 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 130 | ### Running A Callback |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 131 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 132 | Callbacks can be run with their `Run` method, which has the same signature as |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 133 | the template argument to the callback. Note that `base::OnceCallback::Run` |
| 134 | consumes the callback object and can only be invoked on a callback rvalue. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 135 | |
| 136 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 137 | void DoSomething(const base::Callback<void(int, std::string)>& callback) { |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 138 | callback.Run(5, "hello"); |
| 139 | } |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 140 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 141 | void DoSomethingOther(base::OnceCallback<void(int, std::string)> callback) { |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 142 | std::move(callback).Run(5, "hello"); |
| 143 | } |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 144 | ``` |
| 145 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 146 | RepeatingCallbacks can be run more than once (they don't get deleted or marked |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 147 | when run). However, this precludes using `base::Passed` (see below). |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 148 | |
| 149 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 150 | void DoSomething(const base::RepeatingCallback<double(double)>& callback) { |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 151 | double myresult = callback.Run(3.14159); |
| 152 | myresult += callback.Run(2.71828); |
| 153 | } |
| 154 | ``` |
| 155 | |
michaelpg | 0f156e1 | 2017-03-18 02:49:09 | [diff] [blame] | 156 | If running a callback could result in its own destruction (e.g., if the callback |
| 157 | recipient deletes the object the callback is a member of), the callback should |
Bence Béky | 1532745 | 2018-05-10 20:59:07 | [diff] [blame] | 158 | be moved before it can be safely invoked. (Note that this is only an issue for |
| 159 | RepeatingCallbacks, because a OnceCallback always has to be moved for |
| 160 | execution.) |
michaelpg | 0f156e1 | 2017-03-18 02:49:09 | [diff] [blame] | 161 | |
| 162 | ```cpp |
| 163 | void Foo::RunCallback() { |
Bence Béky | 1532745 | 2018-05-10 20:59:07 | [diff] [blame] | 164 | std::move(&foo_deleter_callback_).Run(); |
michaelpg | 0f156e1 | 2017-03-18 02:49:09 | [diff] [blame] | 165 | } |
| 166 | ``` |
| 167 | |
Peter Kasting | 341e1fb | 2018-02-24 00:03:01 | [diff] [blame] | 168 | ### Creating a Callback That Does Nothing |
| 169 | |
| 170 | Sometimes you need a callback that does nothing when run (e.g. test code that |
| 171 | doesn't care to be notified about certain types of events). It may be tempting |
| 172 | to pass a default-constructed callback of the right type: |
| 173 | |
| 174 | ```cpp |
| 175 | using MyCallback = base::OnceCallback<void(bool arg)>; |
| 176 | void MyFunction(MyCallback callback) { |
| 177 | std::move(callback).Run(true); // Uh oh... |
| 178 | } |
| 179 | ... |
| 180 | MyFunction(MyCallback()); // ...this will crash when Run()! |
| 181 | ``` |
| 182 | |
| 183 | Default-constructed callbacks are null, and thus cannot be Run(). Instead, use |
| 184 | `base::DoNothing()`: |
| 185 | |
| 186 | ```cpp |
| 187 | ... |
| 188 | MyFunction(base::DoNothing()); // Can be Run(), will no-op |
| 189 | ``` |
| 190 | |
| 191 | `base::DoNothing()` can be passed for any OnceCallback or RepeatingCallback that |
| 192 | returns void. |
| 193 | |
| 194 | Implementation-wise, `base::DoNothing()` is actually a functor which produces a |
| 195 | callback from `operator()`. This makes it unusable when trying to bind other |
| 196 | arguments to it. Normally, the only reason to bind arguments to DoNothing() is |
| 197 | to manage object lifetimes, and in these cases, you should strive to use idioms |
| 198 | like DeleteSoon(), ReleaseSoon(), or RefCountedDeleteOnSequence instead. If you |
| 199 | truly need to bind an argument to DoNothing(), or if you need to explicitly |
| 200 | create a callback object (because implicit conversion through operator()() won't |
| 201 | compile), 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()! |
| 206 | base::Bind(base::DoNothing::Once<scoped_refptr<Foo>>(), foo_ptr); |
| 207 | ``` |
| 208 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 209 | ### Passing Unbound Input Parameters |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 210 | |
| 211 | Unbound parameters are specified at the time a callback is `Run()`. They are |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 212 | specified in the `base::Callback` template type: |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 213 | |
| 214 | ```cpp |
| 215 | void MyFunc(int i, const std::string& str) {} |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 216 | base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 217 | cb.Run(23, "hello, world"); |
| 218 | ``` |
| 219 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 220 | ### Passing Bound Input Parameters |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 221 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 222 | Bound parameters are specified when you create the callback as arguments to |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 223 | `base::Bind()`. They will be passed to the function and the `Run()`ner of the |
| 224 | callback doesn't see those values or even know that the function it's calling. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 225 | |
| 226 | ```cpp |
| 227 | void MyFunc(int i, const std::string& str) {} |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 228 | base::Callback<void()> cb = base::Bind(&MyFunc, 23, "hello world"); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 229 | cb.Run(); |
| 230 | ``` |
| 231 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 232 | A callback with no unbound input parameters (`base::Callback<void()>`) is |
| 233 | called a `base::Closure`. So we could have also written: |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 234 | |
| 235 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 236 | base::Closure cb = base::Bind(&MyFunc, 23, "hello world"); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 237 | ``` |
| 238 | |
| 239 | When calling member functions, bound parameters just go after the object |
| 240 | pointer. |
| 241 | |
| 242 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 243 | base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world"); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 244 | ``` |
| 245 | |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 246 | ### Partial Binding Of Parameters (Currying) |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 247 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 248 | You can specify some parameters when you create the callback, and specify the |
| 249 | rest when you execute the callback. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 250 | |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 251 | When calling a function bound parameters are first, followed by unbound |
| 252 | parameters. |
| 253 | |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 254 | ```cpp |
| 255 | void ReadIntFromFile(const std::string& filename, |
| 256 | base::OnceCallback<void(int)> on_read); |
| 257 | |
| 258 | void DisplayIntWithPrefix(const std::string& prefix, int result) { |
| 259 | LOG(INFO) << prefix << result; |
| 260 | } |
| 261 | |
| 262 | void AnotherFunc(const std::string& file) { |
| 263 | ReadIntFromFile(file, base::BindOnce(&DisplayIntWithPrefix, "MyPrefix: ")); |
| 264 | }; |
| 265 | ``` |
| 266 | |
| 267 | This technique is known as [Currying](http://en.wikipedia.org/wiki/Currying). It |
| 268 | should be used in lieu of creating an adapter class that holds the bound |
| 269 | arguments. 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 |
| 272 | parameter types if possible. |
| 273 | |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 274 | ### Avoiding Copies With Callback Parameters |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 275 | |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 276 | A parameter of `base::BindRepeating()` or `base::BindOnce()` is moved into its |
| 277 | internal storage if it is passed as a rvalue. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 278 | |
| 279 | ```cpp |
| 280 | std::vector<int> v = {1, 2, 3}; |
| 281 | // |v| is moved into the internal storage without copy. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 282 | base::Bind(&Foo, std::move(v)); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 283 | ``` |
| 284 | |
| 285 | ```cpp |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 286 | // The vector is moved into the internal storage without copy. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 287 | base::Bind(&Foo, std::vector<int>({1, 2, 3})); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 288 | ``` |
| 289 | |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 290 | Arguments bound with `base::BindOnce()` are always moved, if possible, to the |
| 291 | target function. |
| 292 | A function parameter that is passed by value and has a move constructor will be |
| 293 | moved instead of copied. |
| 294 | This makes it easy to use move-only types with `base::BindOnce()`. |
| 295 | |
| 296 | In contrast, arguments bound with `base::BindRepeating()` are only moved to the |
| 297 | target function if the argument is bound with `base::Passed()`. |
| 298 | |
| 299 | **DANGER**: |
| 300 | A `base::RepeatingCallback` can only be run once if arguments were bound with |
| 301 | `base::Passed()`. |
| 302 | For this reason, avoid `base::Passed()`. |
| 303 | If you know a callback will only be called once, prefer to refactor code to |
| 304 | work with `base::OnceCallback` instead. |
| 305 | |
| 306 | Avoid using `base::Passed()` with `base::BindOnce()`, as `std::move()` does the |
| 307 | same thing and is more familiar. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 308 | |
| 309 | ```cpp |
| 310 | void Foo(std::unique_ptr<int>) {} |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 311 | auto p = std::make_unique<int>(42); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 312 | |
| 313 | // |p| is moved into the internal storage of Bind(), and moved out to |Foo|. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 314 | base::BindOnce(&Foo, std::move(p)); |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 315 | base::BindRepeating(&Foo, base::Passed(&p)); // Ok, but subtle. |
| 316 | base::BindRepeating(&Foo, base::Passed(std::move(p))); // Ok, but subtle. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 317 | ``` |
| 318 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 319 | ## Quick reference for advanced binding |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 320 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 321 | ### Binding A Class Method With Weak Pointers |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 322 | |
| 323 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 324 | base::Bind(&MyClass::Foo, GetWeakPtr()); |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 325 | ``` |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 326 | |
| 327 | The callback will not be run if the object has already been destroyed. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 328 | **DANGER**: weak pointers are not threadsafe, so don't use this when passing |
| 329 | between threads! |
| 330 | |
| 331 | To make a weak pointer, you would typically create a |
| 332 | `base::WeakPtrFactory<Foo>` member at the bottom (to ensure it's destroyed |
| 333 | last) of class `Foo`, then call `weak_factory_.GetWeakPtr()`. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 334 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 335 | ### Binding A Class Method With Manual Lifetime Management |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 336 | |
| 337 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 338 | base::Bind(&MyClass::Foo, base::Unretained(this)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 339 | ``` |
| 340 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 341 | This disables all lifetime management on the object. You're responsible for |
| 342 | making sure the object is alive at the time of the call. You break it, you own |
| 343 | it! |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 344 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 345 | ### Binding A Class Method And Having The Callback Own The Class |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 346 | |
| 347 | ```cpp |
| 348 | MyClass* myclass = new MyClass; |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 349 | base::Bind(&MyClass::Foo, base::Owned(myclass)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 350 | ``` |
| 351 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 352 | The 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 |
| 354 | forget" cases. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 355 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 356 | Smart pointers (e.g. `std::unique_ptr<>`) are also supported as the receiver. |
| 357 | |
| 358 | ```cpp |
| 359 | std::unique_ptr<MyClass> myclass(new MyClass); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 360 | base::Bind(&MyClass::Foo, std::move(myclass)); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 361 | ``` |
| 362 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 363 | ### Ignoring Return Values |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 364 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 365 | Sometimes you want to call a function that returns a value in a callback that |
| 366 | doesn't expect a return value. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 367 | |
| 368 | ```cpp |
| 369 | int DoSomething(int arg) { cout << arg << endl; } |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 370 | base::Callback<void(int)> cb = |
| 371 | base::Bind(IgnoreResult(&DoSomething)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 372 | ``` |
| 373 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 374 | ## Quick reference for binding parameters to Bind() |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 375 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 376 | Bound parameters are specified as arguments to `base::Bind()` and are passed to |
| 377 | the function. A callback with no parameters or no unbound parameters is called |
| 378 | a `base::Closure` (`base::Callback<void()>` and `base::Closure` are the same |
| 379 | thing). |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 380 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 381 | ### Passing Parameters Owned By The Callback |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 382 | |
| 383 | ```cpp |
| 384 | void Foo(int* arg) { cout << *arg << endl; } |
| 385 | int* pn = new int(1); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 386 | base::Closure foo_callback = base::Bind(&foo, base::Owned(pn)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 387 | ``` |
| 388 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 389 | The parameter will be deleted when the callback is destroyed, even if it's not |
| 390 | run (like if you post a task during shutdown). |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 391 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 392 | ### Passing Parameters As A unique_ptr |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 393 | |
| 394 | ```cpp |
| 395 | void TakesOwnership(std::unique_ptr<Foo> arg) {} |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 396 | auto f = std::make_unique<Foo>(); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 397 | // f becomes null during the following call. |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 398 | base::OnceClosure cb = base::BindOnce(&TakesOwnership, std::move(f)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 399 | ``` |
| 400 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 401 | Ownership of the parameter will be with the callback until the callback is run, |
| 402 | and then ownership is passed to the callback function. This means the callback |
| 403 | can only be run once. If the callback is never run, it will delete the object |
| 404 | when it's destroyed. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 405 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 406 | ### Passing Parameters As A scoped_refptr |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 407 | |
| 408 | ```cpp |
| 409 | void TakesOneRef(scoped_refptr<Foo> arg) {} |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 410 | scoped_refptr<Foo> f(new Foo); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 411 | base::Closure cb = base::Bind(&TakesOneRef, f); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 412 | ``` |
| 413 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 414 | This should "just work." The closure will take a reference as long as it is |
| 415 | alive, and another reference will be taken for the called function. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 416 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 417 | ```cpp |
| 418 | void DontTakeRef(Foo* arg) {} |
| 419 | scoped_refptr<Foo> f(new Foo); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 420 | base::Closure cb = base::Bind(&DontTakeRef, base::RetainedRef(f)); |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 421 | ``` |
| 422 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 423 | `base::RetainedRef` holds a reference to the object and passes a raw pointer to |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 424 | the object when the Callback is run. |
| 425 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 426 | ### Passing Parameters By Reference |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 427 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 428 | Const references are *copied* unless `base::ConstRef` is used. Example: |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 429 | |
| 430 | ```cpp |
| 431 | void foo(const int& arg) { printf("%d %p\n", arg, &arg); } |
| 432 | int n = 1; |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 433 | base::Closure has_copy = base::Bind(&foo, n); |
| 434 | base::Closure has_ref = base::Bind(&foo, base::ConstRef(n)); |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 435 | n = 2; |
| 436 | foo(n); // Prints "2 0xaaaaaaaaaaaa" |
| 437 | has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb" |
| 438 | has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa" |
| 439 | ``` |
| 440 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 441 | Normally parameters are copied in the closure. |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 442 | **DANGER**: `base::ConstRef` stores a const reference instead, referencing the |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 443 | original parameter. This means that you must ensure the object outlives the |
| 444 | callback! |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 445 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 446 | ## Implementation notes |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 447 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 448 | ### Where Is This Design From: |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 449 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 450 | The 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 |
| 452 | Google. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 453 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 454 | ### Customizing the behavior |
| 455 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 456 | There are several injection points that controls binding behavior from outside |
| 457 | of its implementation. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 458 | |
| 459 | ```cpp |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 460 | namespace base { |
| 461 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 462 | template <typename Receiver> |
| 463 | struct IsWeakReceiver { |
| 464 | static constexpr bool value = false; |
| 465 | }; |
| 466 | |
| 467 | template <typename Obj> |
| 468 | struct UnwrapTraits { |
| 469 | template <typename T> |
| 470 | T&& Unwrap(T&& obj) { |
| 471 | return std::forward<T>(obj); |
| 472 | } |
| 473 | }; |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 474 | |
| 475 | } // namespace base |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 476 | ``` |
| 477 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 478 | If `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 |
| 480 | if it's evaluated to false. You can specialize `base::IsWeakReceiver` to make |
| 481 | an external smart pointer as a weak pointer. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 482 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 483 | `base::UnwrapTraits<BoundObject>::Unwrap()` is called for each bound arguments |
| 484 | right before `base::Callback` calls the target function. You can specialize |
| 485 | this to define an argument wrapper such as `base::Unretained`, |
| 486 | `base::ConstRef`, `base::Owned`, `base::RetainedRef` and `base::Passed`. |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 487 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 488 | ### How The Implementation Works: |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 489 | |
| 490 | There are three main components to the system: |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 491 | 1) The `base::Callback<>` classes. |
| 492 | 2) The `base::Bind()` functions. |
| 493 | 3) The arguments wrappers (e.g., `base::Unretained()` and `base::ConstRef()`). |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 494 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 495 | The Callback classes represent a generic function pointer. Internally, it |
| 496 | stores a refcounted piece of state that represents the target function and all |
| 497 | its bound parameters. The `base::Callback` constructor takes a |
| 498 | `base::BindStateBase*`, which is upcasted from a `base::BindState<>`. In the |
| 499 | context of the constructor, the static type of this `base::BindState<>` pointer |
| 500 | uniquely identifies the function it is representing, all its bound parameters, |
| 501 | and a `Run()` method that is capable of invoking the target. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 502 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 503 | `base::Bind()` creates the `base::BindState<>` that has the full static type, |
| 504 | and erases the target function type as well as the types of the bound |
| 505 | parameters. It does this by storing a pointer to the specific `Run()` function, |
| 506 | and upcasting the state of `base::BindState<>*` to a `base::BindStateBase*`. |
| 507 | This is safe as long as this `BindStateBase` pointer is only used with the |
| 508 | stored `Run()` pointer. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 509 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 510 | To `base::BindState<>` objects are created inside the `base::Bind()` functions. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 511 | These 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 Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 521 | The `base::Bind` functions do the above using type-inference and variadic |
| 522 | templates. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 523 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 524 | By default `base::Bind()` will store copies of all bound parameters, and |
| 525 | attempt to refcount a target object if the function being bound is a class |
| 526 | method. These copies are created even if the function takes parameters as const |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 527 | references. (Binding to non-const references is forbidden, see bind.h.) |
| 528 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 529 | To change this behavior, we introduce a set of argument wrappers (e.g., |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 530 | `base::Unretained()`, and `base::ConstRef()`). These are simple container |
| 531 | templates that are passed by value, and wrap a pointer to argument. See the |
| 532 | file-level comment in base/bind_helpers.h for more info. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 533 | |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 534 | These types are passed to the `Unwrap()` functions to modify the behavior of |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 535 | `base::Bind()`. The `Unwrap()` functions change behavior by doing partial |
tzik | 7c0c0cf1 | 2016-10-05 08:14:05 | [diff] [blame] | 536 | specialization based on whether or not a parameter is a wrapper type. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 537 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 538 | `base::ConstRef()` is similar to `tr1::cref`. `base::Unretained()` is specific |
| 539 | to Chromium. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 540 | |
tzik | a431351 | 2016-09-06 06:51:12 | [diff] [blame] | 541 | ### Missing Functionality |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 542 | - Binding arrays to functions that take a non-const pointer. |
| 543 | Example: |
| 544 | ```cpp |
| 545 | void Foo(const char* ptr); |
| 546 | void Bar(char* ptr); |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 547 | base::Bind(&Foo, "test"); |
| 548 | base::Bind(&Bar, "test"); // This fails because ptr is not const. |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 549 | ``` |
Gayane Petrosyan | 7f71698 | 2018-03-09 15:17:34 | [diff] [blame] | 550 | - In case of partial binding of parameters a possibility of having unbound |
| 551 | parameters before bound parameters. Example: |
| 552 | ```cpp |
| 553 | void Foo(int x, bool y); |
| 554 | base::Bind(&Foo, _1, false); // _1 is a placeholder. |
| 555 | ``` |
tzik | 703f156 | 2016-09-02 07:36:55 | [diff] [blame] | 556 | |
Brett Wilson | 508162c | 2017-09-27 22:24:46 | [diff] [blame] | 557 | If you are thinking of forward declaring `base::Callback` in your own header |
| 558 | file, please include "base/callback_forward.h" instead. |