1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_CALLBACK_H_ 6 #define BASE_CALLBACK_H_ 7 8 #include "base/callback_forward.h" 9 #include "base/callback_internal.h" 10 11 // NOTE: Header files that do not require the full definition of Callback or 12 // Closure should #include "base/callback_forward.h" instead of this file. 13 14 // ----------------------------------------------------------------------------- 15 // Introduction 16 // ----------------------------------------------------------------------------- 17 // 18 // The templated Callback class is a generalized function object. Together 19 // with the Bind() function in bind.h, they provide a type-safe method for 20 // performing partial application of functions. 21 // 22 // Partial application (or "currying") is the process of binding a subset of 23 // a function's arguments to produce another function that takes fewer 24 // arguments. This can be used to pass around a unit of delayed execution, 25 // much like lexical closures are used in other languages. For example, it 26 // is used in Chromium code to schedule tasks on different MessageLoops. 27 // 28 // A callback with no unbound input parameters (base::Callback<void()>) 29 // is called a base::Closure. Note that this is NOT the same as what other 30 // languages refer to as a closure -- it does not retain a reference to its 31 // enclosing environment. 32 // 33 // MEMORY MANAGEMENT AND PASSING 34 // 35 // The Callback objects themselves should be passed by const-reference, and 36 // stored by copy. They internally store their state via a refcounted class 37 // and thus do not need to be deleted. 38 // 39 // The reason to pass via a const-reference is to avoid unnecessary 40 // AddRef/Release pairs to the internal state. 41 // 42 // 43 // ----------------------------------------------------------------------------- 44 // Quick reference for basic stuff 45 // ----------------------------------------------------------------------------- 46 // 47 // BINDING A BARE FUNCTION 48 // 49 // int Return5() { return 5; } 50 // base::Callback<int()> func_cb = base::Bind(&Return5); 51 // LOG(INFO) << func_cb.Run(); // Prints 5. 52 // 53 // BINDING A CLASS METHOD 54 // 55 // The first argument to bind is the member function to call, the second is 56 // the object on which to call it. 57 // 58 // class Ref : public base::RefCountedThreadSafe<Ref> { 59 // public: 60 // int Foo() { return 3; } 61 // void PrintBye() { LOG(INFO) << "bye."; } 62 // }; 63 // scoped_refptr<Ref> ref = new Ref(); 64 // base::Callback<void()> ref_cb = base::Bind(&Ref::Foo, ref); 65 // LOG(INFO) << ref_cb.Run(); // Prints out 3. 66 // 67 // By default the object must support RefCounted or you will get a compiler 68 // error. If you're passing between threads, be sure it's 69 // RefCountedThreadSafe! See "Advanced binding of member functions" below if 70 // you don't want to use reference counting. 71 // 72 // RUNNING A CALLBACK 73 // 74 // Callbacks can be run with their "Run" method, which has the same 75 // signature as the template argument to the callback. 76 // 77 // void DoSomething(const base::Callback<void(int, std::string)>& callback) { 78 // callback.Run(5, "hello"); 79 // } 80 // 81 // Callbacks can be run more than once (they don't get deleted or marked when 82 // run). However, this precludes using base::Passed (see below). 83 // 84 // void DoSomething(const base::Callback<double(double)>& callback) { 85 // double myresult = callback.Run(3.14159); 86 // myresult += callback.Run(2.71828); 87 // } 88 // 89 // PASSING UNBOUND INPUT PARAMETERS 90 // 91 // Unbound parameters are specified at the time a callback is Run(). They are 92 // specified in the Callback template type: 93 // 94 // void MyFunc(int i, const std::string& str) {} 95 // base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc); 96 // cb.Run(23, "hello, world"); 97 // 98 // PASSING BOUND INPUT PARAMETERS 99 // 100 // Bound parameters are specified when you create thee callback as arguments 101 // to Bind(). They will be passed to the function and the Run()ner of the 102 // callback doesn't see those values or even know that the function it's 103 // calling. 104 // 105 // void MyFunc(int i, const std::string& str) {} 106 // base::Callback<void()> cb = base::Bind(&MyFunc, 23, "hello world"); 107 // cb.Run(); 108 // 109 // A callback with no unbound input parameters (base::Callback<void()>) 110 // is called a base::Closure. So we could have also written: 111 // 112 // base::Closure cb = base::Bind(&MyFunc, 23, "hello world"); 113 // 114 // When calling member functions, bound parameters just go after the object 115 // pointer. 116 // 117 // base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world"); 118 // 119 // PARTIAL BINDING OF PARAMETERS 120 // 121 // You can specify some parameters when you create the callback, and specify 122 // the rest when you execute the callback. 123 // 124 // void MyFunc(int i, const std::string& str) {} 125 // base::Callback<void(const std::string&)> cb = base::Bind(&MyFunc, 23); 126 // cb.Run("hello world"); 127 // 128 // When calling a function bound parameters are first, followed by unbound 129 // parameters. 130 // 131 // 132 // ----------------------------------------------------------------------------- 133 // Quick reference for advanced binding 134 // ----------------------------------------------------------------------------- 135 // 136 // BINDING A CLASS METHOD WITH WEAK POINTERS 137 // 138 // base::Bind(&MyClass::Foo, GetWeakPtr()); 139 // 140 // The callback will not be run if the object has already been destroyed. 141 // DANGER: weak pointers are not threadsafe, so don't use this 142 // when passing between threads! 143 // 144 // BINDING A CLASS METHOD WITH MANUAL LIFETIME MANAGEMENT 145 // 146 // base::Bind(&MyClass::Foo, base::Unretained(this)); 147 // 148 // This disables all lifetime management on the object. You're responsible 149 // for making sure the object is alive at the time of the call. You break it, 150 // you own it! 151 // 152 // BINDING A CLASS METHOD AND HAVING THE CALLBACK OWN THE CLASS 153 // 154 // MyClass* myclass = new MyClass; 155 // base::Bind(&MyClass::Foo, base::Owned(myclass)); 156 // 157 // The object will be deleted when the callback is destroyed, even if it's 158 // not run (like if you post a task during shutdown). Potentially useful for 159 // "fire and forget" cases. 160 // 161 // IGNORING RETURN VALUES 162 // 163 // Sometimes you want to call a function that returns a value in a callback 164 // that doesn't expect a return value. 165 // 166 // int DoSomething(int arg) { cout << arg << endl; } 167 // base::Callback<void(int)> cb = 168 // base::Bind(base::IgnoreResult(&DoSomething)); 169 // 170 // 171 // ----------------------------------------------------------------------------- 172 // Quick reference for binding parameters to Bind() 173 // ----------------------------------------------------------------------------- 174 // 175 // Bound parameters are specified as arguments to Bind() and are passed to the 176 // function. A callback with no parameters or no unbound parameters is called a 177 // Closure (base::Callback<void()> and base::Closure are the same thing). 178 // 179 // PASSING PARAMETERS OWNED BY THE CALLBACK 180 // 181 // void Foo(int* arg) { cout << *arg << endl; } 182 // int* pn = new int(1); 183 // base::Closure foo_callback = base::Bind(&foo, base::Owned(pn)); 184 // 185 // The parameter will be deleted when the callback is destroyed, even if it's 186 // not run (like if you post a task during shutdown). 187 // 188 // PASSING PARAMETERS AS A scoped_ptr 189 // 190 // void TakesOwnership(std::unique_ptr<Foo> arg) {} 191 // std::unique_ptr<Foo> f(new Foo); 192 // // f becomes null during the following call. 193 // base::Closure cb = base::Bind(&TakesOwnership, base::Passed(&f)); 194 // 195 // Ownership of the parameter will be with the callback until the it is run, 196 // when ownership is passed to the callback function. This means the callback 197 // can only be run once. If the callback is never run, it will delete the 198 // object when it's destroyed. 199 // 200 // PASSING PARAMETERS AS A scoped_refptr 201 // 202 // void TakesOneRef(scoped_refptr<Foo> arg) {} 203 // scoped_refptr<Foo> f(new Foo) 204 // base::Closure cb = base::Bind(&TakesOneRef, f); 205 // 206 // This should "just work." The closure will take a reference as long as it 207 // is alive, and another reference will be taken for the called function. 208 // 209 // PASSING PARAMETERS BY REFERENCE 210 // 211 // Const references are *copied* unless ConstRef is used. Example: 212 // 213 // void foo(const int& arg) { printf("%d %p\n", arg, &arg); } 214 // int n = 1; 215 // base::Closure has_copy = base::Bind(&foo, n); 216 // base::Closure has_ref = base::Bind(&foo, base::ConstRef(n)); 217 // n = 2; 218 // foo(n); // Prints "2 0xaaaaaaaaaaaa" 219 // has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb" 220 // has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa" 221 // 222 // Normally parameters are copied in the closure. DANGER: ConstRef stores a 223 // const reference instead, referencing the original parameter. This means 224 // that you must ensure the object outlives the callback! 225 // 226 // 227 // ----------------------------------------------------------------------------- 228 // Implementation notes 229 // ----------------------------------------------------------------------------- 230 // 231 // WHERE IS THIS DESIGN FROM: 232 // 233 // The design Callback and Bind is heavily influenced by C++'s 234 // tr1::function/tr1::bind, and by the "Google Callback" system used inside 235 // Google. 236 // 237 // 238 // HOW THE IMPLEMENTATION WORKS: 239 // 240 // There are three main components to the system: 241 // 1) The Callback classes. 242 // 2) The Bind() functions. 243 // 3) The arguments wrappers (e.g., Unretained() and ConstRef()). 244 // 245 // The Callback classes represent a generic function pointer. Internally, 246 // it stores a refcounted piece of state that represents the target function 247 // and all its bound parameters. Each Callback specialization has a templated 248 // constructor that takes an BindState<>*. In the context of the constructor, 249 // the static type of this BindState<> pointer uniquely identifies the 250 // function it is representing, all its bound parameters, and a Run() method 251 // that is capable of invoking the target. 252 // 253 // Callback's constructor takes the BindState<>* that has the full static type 254 // and erases the target function type as well as the types of the bound 255 // parameters. It does this by storing a pointer to the specific Run() 256 // function, and upcasting the state of BindState<>* to a 257 // BindStateBase*. This is safe as long as this BindStateBase pointer 258 // is only used with the stored Run() pointer. 259 // 260 // To BindState<> objects are created inside the Bind() functions. 261 // These functions, along with a set of internal templates, are responsible for 262 // 263 // - Unwrapping the function signature into return type, and parameters 264 // - Determining the number of parameters that are bound 265 // - Creating the BindState storing the bound parameters 266 // - Performing compile-time asserts to avoid error-prone behavior 267 // - Returning an Callback<> with an arity matching the number of unbound 268 // parameters and that knows the correct refcounting semantics for the 269 // target object if we are binding a method. 270 // 271 // The Bind functions do the above using type-inference, and template 272 // specializations. 273 // 274 // By default Bind() will store copies of all bound parameters, and attempt 275 // to refcount a target object if the function being bound is a class method. 276 // These copies are created even if the function takes parameters as const 277 // references. (Binding to non-const references is forbidden, see bind.h.) 278 // 279 // To change this behavior, we introduce a set of argument wrappers 280 // (e.g., Unretained(), and ConstRef()). These are simple container templates 281 // that are passed by value, and wrap a pointer to argument. See the 282 // file-level comment in base/bind_helpers.h for more info. 283 // 284 // These types are passed to the Unwrap() functions, and the MaybeRefcount() 285 // functions respectively to modify the behavior of Bind(). The Unwrap() 286 // and MaybeRefcount() functions change behavior by doing partial 287 // specialization based on whether or not a parameter is a wrapper type. 288 // 289 // ConstRef() is similar to tr1::cref. Unretained() is specific to Chromium. 290 // 291 // 292 // WHY NOT TR1 FUNCTION/BIND? 293 // 294 // Direct use of tr1::function and tr1::bind was considered, but ultimately 295 // rejected because of the number of copy constructors invocations involved 296 // in the binding of arguments during construction, and the forwarding of 297 // arguments during invocation. These copies will no longer be an issue in 298 // C++0x because C++0x will support rvalue reference allowing for the compiler 299 // to avoid these copies. However, waiting for C++0x is not an option. 300 // 301 // Measured with valgrind on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5), the 302 // tr1::bind call itself will invoke a non-trivial copy constructor three times 303 // for each bound parameter. Also, each when passing a tr1::function, each 304 // bound argument will be copied again. 305 // 306 // In addition to the copies taken at binding and invocation, copying a 307 // tr1::function causes a copy to be made of all the bound parameters and 308 // state. 309 // 310 // Furthermore, in Chromium, it is desirable for the Callback to take a 311 // reference on a target object when representing a class method call. This 312 // is not supported by tr1. 313 // 314 // Lastly, tr1::function and tr1::bind has a more general and flexible API. 315 // This includes things like argument reordering by use of 316 // tr1::bind::placeholder, support for non-const reference parameters, and some 317 // limited amount of subtyping of the tr1::function object (e.g., 318 // tr1::function<int(int)> is convertible to tr1::function<void(int)>). 319 // 320 // These are not features that are required in Chromium. Some of them, such as 321 // allowing for reference parameters, and subtyping of functions, may actually 322 // become a source of errors. Removing support for these features actually 323 // allows for a simpler implementation, and a terser Currying API. 324 // 325 // 326 // WHY NOT GOOGLE CALLBACKS? 327 // 328 // The Google callback system also does not support refcounting. Furthermore, 329 // its implementation has a number of strange edge cases with respect to type 330 // conversion of its arguments. In particular, the argument's constness must 331 // at times match exactly the function signature, or the type-inference might 332 // break. Given the above, writing a custom solution was easier. 333 // 334 // 335 // MISSING FUNCTIONALITY 336 // - Invoking the return of Bind. Bind(&foo).Run() does not work; 337 // - Binding arrays to functions that take a non-const pointer. 338 // Example: 339 // void Foo(const char* ptr); 340 // void Bar(char* ptr); 341 // Bind(&Foo, "test"); 342 // Bind(&Bar, "test"); // This fails because ptr is not const. 343 // 344 // If you are thinking of forward declaring Callback in your own header file, 345 // please include "base/callback_forward.h" instead. 346 347 namespace base { 348 349 template <typename R, typename... Args, internal::CopyMode copy_mode> 350 class Callback<R(Args...), copy_mode> 351 : public internal::CallbackBase<copy_mode> { 352 private: 353 using PolymorphicInvoke = R (*)(internal::BindStateBase*, Args&&...); 354 355 public: 356 // MSVC 2013 doesn't support Type Alias of function types. 357 // Revisit this after we update it to newer version. 358 typedef R RunType(Args...); 359 360 Callback() : internal::CallbackBase<copy_mode>(nullptr) {} 361 362 Callback(internal::BindStateBase* bind_state, 363 PolymorphicInvoke invoke_func) 364 : internal::CallbackBase<copy_mode>(bind_state) { 365 using InvokeFuncStorage = 366 typename internal::CallbackBase<copy_mode>::InvokeFuncStorage; 367 this->polymorphic_invoke_ = 368 reinterpret_cast<InvokeFuncStorage>(invoke_func); 369 } 370 371 bool Equals(const Callback& other) const { 372 return this->EqualsInternal(other); 373 } 374 375 // Run() makes an extra copy compared to directly calling the bound function 376 // if an argument is passed-by-value and is copyable-but-not-movable: 377 // i.e. below copies CopyableNonMovableType twice. 378 // void F(CopyableNonMovableType) {} 379 // Bind(&F).Run(CopyableNonMovableType()); 380 // 381 // We can not fully apply Perfect Forwarding idiom to the callchain from 382 // Callback::Run() to the target function. Perfect Forwarding requires 383 // knowing how the caller will pass the arguments. However, the signature of 384 // InvokerType::Run() needs to be fixed in the callback constructor, so Run() 385 // cannot template its arguments based on how it's called. 386 R Run(Args... args) const { 387 PolymorphicInvoke f = 388 reinterpret_cast<PolymorphicInvoke>(this->polymorphic_invoke_); 389 return f(this->bind_state_.get(), std::forward<Args>(args)...); 390 } 391 }; 392 393 } // namespace base 394 395 #endif // BASE_CALLBACK_H_ 396