Callback<> and Bind()

Contents

When you pass a base::{Once,Repeating}Callback object to a function parameter, use std::move() if you don‘t need to keep a reference to it, otherwise, pass the object directly. You may see a compile error when the function requires the exclusive ownership, and you didn’t pass the callback by move. Note that the moved-from base::{Once,Repeating}Callback becomes null, as if its Reset() method had been called. Afterward, its is_null() method will return true and its operator bool() will return false.

Quick reference for basic stuff

Binding A Bare Function

  1. int Return5() { return 5; }
  2. base::OnceCallback<int()> func_cb = base::BindOnce(&Return5);
  3. LOG(INFO) << std::move(func_cb).Run(); // Prints 5.
  4. int Return5() { return 5; }
  5. base::RepeatingCallback<int()> func_cb = base::BindRepeating(&Return5);
  6. LOG(INFO) << func_cb.Run(); // Prints 5.

Binding A Captureless Lambda

  1. base::Callback<int()> lambda_cb = base::Bind([] { return 4; });
  2. LOG(INFO) << lambda_cb.Run(); // Print 4.
  3. base::OnceCallback<int()> lambda_cb2 = base::BindOnce([] { return 3; });
  4. LOG(INFO) << std::move(lambda_cb2).Run(); // Print 3.
  5. base::OnceCallback<int()> lambda_cb3 = base::BindOnce([] { return 2; });
  6. base::OnceCallback<int(base::OnceCallback<int()>)> lambda_cb4 =
  7. base::BindOnce(
  8. [](base::OnceCallback<int()> callback) {
  9. return std::move(callback).Run(); },
  10. std::move(lambda_cb3));
  11. LOG(INFO) << std::move(lambda_cb4).Run(); // Print 2.

Binding A Capturing Lambda (In Tests)

When writing tests, it is often useful to capture arguments that need to be modified in a callback.

  1. #include "base/test/bind_test_util.h"
  2. int i = 2;
  3. base::Callback<void()> lambda_cb = base::BindLambdaForTesting([&]() { i++; });
  4. lambda_cb.Run();
  5. LOG(INFO) << i; // Print 3;

Binding A Class Method

The first argument to bind is the member function to call, the second is the object on which to call it.

  1. class Ref : public base::RefCountedThreadSafe<Ref> {
  2. public:
  3. int Foo() { return 3; }
  4. };
  5. scoped_refptr<Ref> ref = new Ref();
  6. base::Callback<void()> ref_cb = base::Bind(&Ref::Foo, ref);
  7. LOG(INFO) << ref_cb.Run(); // Prints out 3.

By default the object must support RefCounted or you will get a compiler error. If you‘re passing between threads, be sure it’s RefCountedThreadSafe! See “Advanced binding of member functions” below if you don’t want to use reference counting.

Running A Callback

Callbacks can be run with their Run method, which has the same signature as the template argument to the callback. Note that base::OnceCallback::Run consumes the callback object and can only be invoked on a callback rvalue.

  1. void DoSomething(const base::Callback<void(int, std::string)>& callback) {
  2. callback.Run(5, "hello");
  3. }
  4. void DoSomethingOther(base::OnceCallback<void(int, std::string)> callback) {
  5. std::move(callback).Run(5, "hello");
  6. }

RepeatingCallbacks can be run more than once (they don’t get deleted or marked when run). However, this precludes using base::Passed (see below).

  1. void DoSomething(const base::RepeatingCallback<double(double)>& callback) {
  2. double myresult = callback.Run(3.14159);
  3. myresult += callback.Run(2.71828);
  4. }

If running a callback could result in its own destruction (e.g., if the callback recipient deletes the object the callback is a member of), the callback should be moved before it can be safely invoked. (Note that this is only an issue for RepeatingCallbacks, because a OnceCallback always has to be moved for execution.)

  1. void Foo::RunCallback() {
  2. std::move(&foo_deleter_callback_).Run();
  3. }

Creating a Callback That Does Nothing

Sometimes you need a callback that does nothing when run (e.g. test code that doesn’t care to be notified about certain types of events). It may be tempting to pass a default-constructed callback of the right type:

  1. using MyCallback = base::OnceCallback<void(bool arg)>;
  2. void MyFunction(MyCallback callback) {
  3. std::move(callback).Run(true); // Uh oh...
  4. }
  5. ...
  6. MyFunction(MyCallback()); // ...this will crash when Run()!
  7. Default-constructed callbacks are null, and thus cannot be Run(). Instead, use base::DoNothing():
  8. ...
  9. MyFunction(base::DoNothing()); // Can be Run(), will no-op

base::DoNothing() can be passed for any OnceCallback or RepeatingCallback that returns void.
Implementation-wise, base::DoNothing() is actually a functor which produces a callback from operator(). This makes it unusable when trying to bind other arguments to it. Normally, the only reason to bind arguments to DoNothing() is to manage object lifetimes, and in these cases, you should strive to use idioms like DeleteSoon(), ReleaseSoon(), or RefCountedDeleteOnSequence instead. If you truly need to bind an argument to DoNothing(), or if you need to explicitly create a callback object (because implicit conversion through operator()() won’t compile), you can instantiate directly:

  1. // Binds |foo_ptr| to a no-op OnceCallback takes a scoped_refptr<Foo>.
  2. // ANTIPATTERN WARNING: This should likely be changed to ReleaseSoon()!
  3. base::Bind(base::DoNothing::Once<scoped_refptr<Foo>>(), foo_ptr);

Passing Unbound Input Parameters

Unbound parameters are specified at the time a callback is Run(). They are specified in the base::Callback template type:

  1. void MyFunc(int i, const std::string& str) {}
  2. base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc);
  3. cb.Run(23, "hello, world");

Passing Bound Input Parameters

Bound parameters are specified when you create the callback as arguments to base::Bind(). They will be passed to the function and the Run()ner of the callback doesn‘t see those values or even know that the function it’s calling.

  1. void MyFunc(int i, const std::string& str) {}
  2. base::Callback<void()> cb = base::Bind(&MyFunc, 23, "hello world");
  3. cb.Run();

A callback with no unbound input parameters (base::Callback<void()>) is called a base::Closure. So we could have also written:

  1. base::Closure cb = base::Bind(&MyFunc, 23, "hello world");

When calling member functions, bound parameters just go after the object pointer.

  1. base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world");

Partial Binding Of Parameters

You can specify some parameters when you create the callback, and specify the rest when you execute the callback.
When calling a function bound parameters are first, followed by unbound parameters.

  1. void ReadIntFromFile(const std::string& filename,
  2. base::OnceCallback<void(int)> on_read);
  3. void DisplayIntWithPrefix(const std::string& prefix, int result) {
  4. LOG(INFO) << prefix << result;
  5. }
  6. void AnotherFunc(const std::string& file) {
  7. ReadIntFromFile(file, base::BindOnce(&DisplayIntWithPrefix, "MyPrefix: "));
  8. };

This technique is known as partial application. It should be used in lieu of creating an adapter class that holds the bound arguments. Notice also that the "MyPrefix: " argument is actually a const char*, while DisplayIntWithPrefix actually wants a const std::string&. Like normal function dispatch, base::Bind, will coerce parameter types if possible.

Avoiding Copies With Callback Parameters

A parameter of base::BindRepeating() or base::BindOnce() is moved into its internal storage if it is passed as a rvalue.

  1. std::vector<int> v = {1, 2, 3};
  2. // |v| is moved into the internal storage without copy.
  3. base::Bind(&Foo, std::move(v));
  4. // The vector is moved into the internal storage without copy.
  5. base::Bind(&Foo, std::vector<int>({1, 2, 3}));

Arguments bound with base::BindOnce() are always moved, if possible, to the target function. A function parameter that is passed by value and has a move constructor will be moved instead of copied. This makes it easy to use move-only types with base::BindOnce().
In contrast, arguments bound with base::BindRepeating() are only moved to the target function if the argument is bound with base::Passed().
DANGER: A base::RepeatingCallback can only be run once if arguments were bound with base::Passed(). For this reason, avoid base::Passed(). If you know a callback will only be called once, prefer to refactor code to work with base::OnceCallback instead.
Avoid using base::Passed() with base::BindOnce(), as std::move() does the same thing and is more familiar.

  1. void Foo(std::unique_ptr<int>) {}
  2. auto p = std::make_unique<int>(42);
  3. // |p| is moved into the internal storage of Bind(), and moved out to |Foo|.
  4. base::BindOnce(&Foo, std::move(p));
  5. base::BindRepeating(&Foo, base::Passed(&p)); // Ok, but subtle.
  6. base::BindRepeating(&Foo, base::Passed(std::move(p))); // Ok, but subtle.

Quick reference for advanced binding

Binding A Class Method With Weak Pointers

If MyClass has a base::WeakPtr<MyClass> weak_this_ member (see below) then a class method can be bound with:

  1. base::Bind(&MyClass::Foo, weak_this_);

The callback will not be run if the object has already been destroyed.
Note that class method callbacks bound to base::WeakPtrs may only be run on the same sequence on which the object will be destroyed, since otherwise execution of the callback might race with the object’s deletion.
To use base::WeakPtr with base::Bind(), MyClass will typically look like:

  1. class MyClass {
  2. public:
  3. MyClass() {
  4. weak_this_ = weak_factory_.GetWeakPtr();
  5. }
  6. private:
  7. base::WeakPtr<MyClass> weak_this_;
  8. // MyClass member variables go here.
  9. base::WeakPtrFactory<MyClass> weak_factory_{this};
  10. };

weak_factory_ is the last member variable in MyClass so that it is destroyed first. This ensures that if any class methods bound to weak_this_are Run() during teardown, then they will not actually be executed.
If MyClass only ever base::Bind()s and executes callbacks on the same sequence, then it is generally safe to call weak_factory_.GetWeakPtr() at the base::Bind() call, rather than taking a separate weak_this_ during construction.

Binding A Class Method With Manual Lifetime Management

  1. base::Bind(&MyClass::Foo, base::Unretained(this));

This disables all lifetime management on the object. You’re responsible for making sure the object is alive at the time of the call. You break it, you own it!

Binding A Class Method And Having The Callback Own The Class

  1. MyClass* myclass = new MyClass;
  2. base::Bind(&MyClass::Foo, base::Owned(myclass));

The object will be deleted when the callback is destroyed, even if it’s not run (like if you post a task during shutdown). Potentially useful for “fire and forget” cases.
Smart pointers (e.g. std::unique_ptr<>) are also supported as the receiver.

  1. std::unique_ptr<MyClass> myclass(new MyClass);
  2. base::Bind(&MyClass::Foo, std::move(myclass));

Ignoring Return Values

Sometimes you want to call a function that returns a value in a callback that doesn’t expect a return value.

  1. int DoSomething(int arg) { cout << arg << endl; }
  2. base::Callback<void(int)> cb = base::Bind(IgnoreResult(&DoSomething));

Quick reference for binding parameters to Bind()

Bound parameters are specified as arguments to base::Bind() and are passed to the function. A callback with no parameters or no unbound parameters is called a base::Closure (base::Callback<void()> and base::Closure are the same thing).

Passing Parameters Owned By The Callback

  1. void Foo(int* arg) { cout << *arg << endl; }
  2. int* pn = new int(1);
  3. base::Closure foo_callback = base::Bind(&foo, base::Owned(pn));

The parameter will be deleted when the callback is destroyed, even if it’s not run (like if you post a task during shutdown).

Passing Parameters As A unique_ptr

  1. void TakesOwnership(std::unique_ptr<Foo> arg) {}
  2. auto f = std::make_unique<Foo>();
  3. // f becomes null during the following call.
  4. base::OnceClosure cb = base::BindOnce(&TakesOwnership, std::move(f));

Ownership of the parameter will be with the callback until the callback is run, and then ownership is passed to the callback function. This means the callback can only be run once. If the callback is never run, it will delete the object when it’s destroyed.

Passing Parameters As A scoped_refptr

  1. void TakesOneRef(scoped_refptr<Foo> arg) {}
  2. scoped_refptr<Foo> f(new Foo);
  3. base::Closure cb = base::Bind(&TakesOneRef, f);

This should “just work.” The closure will take a reference as long as it is alive, and another reference will be taken for the called function.

  1. void DontTakeRef(Foo* arg) {}
  2. scoped_refptr<Foo> f(new Foo);
  3. base::Closure cb = base::Bind(&DontTakeRef, base::RetainedRef(f));

base::RetainedRef holds a reference to the object and passes a raw pointer to the object when the Callback is run.

Passing Parameters By Reference

References are copied unless std::ref or std::cref is used. Example:

  1. void foo(const int& arg) { printf("%d %p\n", arg, &arg); }
  2. int n = 1;
  3. base::Closure has_copy = base::Bind(&foo, n);
  4. base::Closure has_ref = base::Bind(&foo, std::cref(n));
  5. n = 2;
  6. foo(n); // Prints "2 0xaaaaaaaaaaaa"
  7. has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb"
  8. has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa"

Normally parameters are copied in the closure. DANGER: std::ref and std::cref store a (const) reference instead, referencing the original parameter. This means that you must ensure the object outlives the callback!

Implementation notes

Where Is This Design From:

The design of base::Callback and base::Bind is heavily influenced by C++’s tr1::function / tr1::bind, and by the “Google Callback” system used inside Google.

Customizing the behavior

There are several injection points that controls binding behavior from outside of its implementation.

If base::IsWeakReceiver<Receiver>::value is true on a receiver of a method, base::Bind checks if the receiver is evaluated to true and cancels the invocation if it’s evaluated to false. You can specialize base::IsWeakReceiver to make an external smart pointer as a weak pointer.
base::UnwrapTraits<BoundObject>::Unwrap() is called for each bound arguments right before base::Callback calls the target function. You can specialize this to define an argument wrapper such as base::Unretained, base::Owned, base::RetainedRef and base::Passed.

How The Implementation Works:

There are three main components to the system:

  1. The base::Callback<> classes.
  2. The base::Bind() functions.
  3. The arguments wrappers (e.g., base::Unretained() and base::Owned()).

The Callback classes represent a generic function pointer. Internally, it stores a refcounted piece of state that represents the target function and all its bound parameters. The base::Callback constructor takes a base::BindStateBase*, which is upcasted from a base::BindState<>. In the context of the constructor, the static type of this base::BindState<> pointer uniquely identifies the function it is representing, all its bound parameters, and a Run() method that is capable of invoking the target.
base::Bind() creates the base::BindState<> that has the full static type, and erases the target function type as well as the types of the bound parameters. It does this by storing a pointer to the specific Run() function, and upcasting the state of base::BindState<>* to a base::BindStateBase*. This is safe as long as this BindStateBase pointer is only used with the stored Run() pointer.
To base::BindState<> objects are created inside the base::Bind() functions. These functions, along with a set of internal templates, are responsible for

  • Unwrapping the function signature into return type, and parameters
  • Determining the number of parameters that are bound
  • Creating the BindState storing the bound parameters
  • Performing compile-time asserts to avoid error-prone behavior
  • Returning a Callback<> with an arity matching the number of unbound parameters and that knows the correct refcounting semantics for the target object if we are binding a method.

The base::Bind functions do the above using type-inference and variadic templates.
By default base::Bind() will store copies of all bound parameters, and attempt to refcount a target object if the function being bound is a class method. These copies are created even if the function takes parameters as const references. (Binding to non-const references is forbidden, see bind.h.)
To change this behavior, we introduce a set of argument wrappers (e.g., base::Unretained()). These are simple container templates that are passed by value, and wrap a pointer to argument. See the file-level comment in base/bind_helpers.h for more info.
These types are passed to the Unwrap() functions to modify the behavior of base::Bind(). The Unwrap() functions change behavior by doing partial specialization based on whether or not a parameter is a wrapper type.
base::Unretained() is specific to Chromium.

Missing Functionality

  • Binding arrays to functions that take a non-const pointer. Example:

    1. void Foo(const char* ptr);
    2. void Bar(char* ptr);
    3. base::Bind(&Foo, "test");
    4. base::Bind(&Bar, "test"); // This fails because ptr is not const.
  • In case of partial binding of parameters a possibility of having unbound parameters before bound parameters. Example:

    1. void Foo(int x, bool y);
    2. base::Bind(&Foo, _1, false); // _1 is a placeholder.


    If you are thinking of forward declaring base::Callback in your own header file, please include “base/callback_forward.h” instead.

Powered by Gitiles| Privac