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