chromium Callback 部分翻译
来源:互联网 发布:淘宝怎么能提高流量 编辑:程序博客网 时间:2024/05/15 23:53
// -----------------------------------------------------------------------------// Introduction// -----------------------------------------------------------------------------//// The templated Callback class is a generalized function object. Together// with the Bind() function in bind.h, they provide a type-safe method for// performing partial application of functions.// 这个Callback模板类是一个普通的函数对象(注意不是函数定义是对象/实例),一般与Bind函数一起使用,// 他们为局部函数或局部类成员函数提供一种类型安全的访问机制。// Partial application (or "currying") is the process of binding a subset of// a function's arguments to produce another function that takes fewer// arguments. This can be used to pass around a unit of delayed execution,// much like lexical closures are used in other languages. For example, it// is used in Chromium code to schedule tasks on different MessageLoops.// 局部化应用是这样的一个处理过程:绑定一个函数的参数的子集,生成一个需要更少参数的函数供人使用// 可以用于传递一个延迟执行的单元,类似于其他语言中的闭包的功能。// pointer A;// function funA(A a){ a->dosomething();}// function funACallback(){a->dosomething();} //其他应用程序不知道有a这个实例,只需要直接调用funACallback()//// A callback with no unbound input parameters (base::Callback<void(void)>)// is called a base::Closure. Note that this is NOT the same as what other// languages refer to as a closure -- it does not retain a reference to its// enclosing environment.// 没有任何参数和返回值的Callback实例,叫做base::Closure(上面举的例子funACallback()就是)// base::Callback<void(void)> 等于 base::Closure//// MEMORY MANAGEMENT AND PASSING//// The Callback objects themselves should be passed by const-reference, and// stored by copy. They internally store their state via a refcounted class// and thus do not need to be deleted.// // The reason to pass via a const-reference is to avoid unnecessary// AddRef/Release pairs to the internal state.// Callback实例都是值引用的,这样可以减少使用引用计数的麻烦//// -----------------------------------------------------------------------------// Quick reference for basic stuff// -----------------------------------------------------------------------------//// BINDING A BARE FUNCTION 绑定一个普通的函数//// int Return5() { return 5; }// base::Callback<int(void)> func_cb = base::Bind(&Return5);// LOG(INFO) << func_cb.Run(); // Prints 5.//// 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.//// class Ref : public base::RefCountedThreadSafe<Ref> {// public:// int Foo() { return 3; }// void PrintBye() { LOG(INFO) << "bye."; }// };// scoped_refptr<Ref> ref = new Ref();// base::Callback<void(void)> ref_cb = base::Bind(&Ref::Foo, ref);// 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.// 被绑定的类实例必须支持RefCounted,否则将会编译不通过,// 如果要跨线程使用,则必须继承RefCountedThreadSafe// // RUNNING A CALLBACK//// Callbacks can be run with their "Run" method, which has the same// signature as the template argument to the callback.// 要运行Callback可以直接调用它们的Run方法,如果有参数当然要传递参数给它,// 参数跟模板参数一致,后面还会有这方面的说明//// void DoSomething(const base::Callback<void(int, std::string)>& callback) {// callback.Run(5, "hello");// }//// Callbacks can be run more than once (they don't get deleted or marked when// run). However, this precludes using base::Passed (see below).// 除了使用了base::Passed的Callback之外,其他情况一般来说一个Callback可以运行多次//// void DoSomething(const base::Callback<double(double)>& callback) {// double myresult = callback.Run(3.14159);// myresult += callback.Run(2.71828);// }//// PASSING UNBOUND INPUT PARAMETERS 传入参数//// Unbound parameters are specified at the time a callback is Run(). They are// specified in the Callback template type://// void MyFunc(int i, const std::string& str) {}// base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc);// cb.Run(23, "hello, world");//// PASSING BOUND INPUT PARAMETERS 绑定全部参数// 在绑定的时候设置了参数值的话,调用的时候就不用再传了//// Bound parameters are specified when you create thee callback as arguments// to 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.//// void MyFunc(int i, const std::string& str) {}// base::Callback<void(void)> cb = base::Bind(&MyFunc, 23, "hello world");// cb.Run();//// A callback with no unbound input parameters (base::Callback<void(void)>)// is called a base::Closure. So we could have also written://// base::Closure cb = base::Bind(&MyFunc, 23, "hello world");//// When calling member functions, bound parameters just go after the object// pointer.如果是成员函数,当前实例的指针一定要绑定,而且是在第二个参数//// 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.//// void MyFunc(int i, const std::string& str) {}// base::Callback<void(const std::string&)> cb = base::Bind(&MyFunc, 23);// cb.Run("hello world");//// When calling a function bound parameters are first, followed by unbound// parameters.////// -----------------------------------------------------------------------------// Quick reference for advanced binding// -----------------------------------------------------------------------------//// BINDING A CLASS METHOD WITH WEAK POINTERS// 所谓弱指针,是指这些指针所指向的对象可以已经不存在,已经被销毁// 不过要注意,弱指针不是线程安全的,所以不要再多线程场景下使用//// base::Bind(&MyClass::Foo, GetWeakPtr());//// The callback will not be issued if the object is destroyed at the time// it's issued. DANGER: weak pointers are not threadsafe, so don't use this// when passing between threads!//// BINDING A CLASS METHOD WITH MANUAL LIFETIME MANAGEMENT // 绑定自己管理声明周期的对象,你要保证在执行这个callback的时候,这个对象还存在//// 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// 让绑定的对象跟着Callback对象一起死(销毁~~~),Callback执行之后就无用的对象最适合了//// MyClass* myclass = new MyClass;// 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.//// IGNORING RETURN VALUES 如果不关心返回值的话,可以这样绑定//// Sometimes you want to call a function that returns a value in a callback// that doesn't expect a return value.//// int DoSomething(int arg) { cout << arg << endl; }// base::Callback<void<int>) cb =// base::Bind(base::IgnoreResult(&DoSomething));////// -----------------------------------------------------------------------------// Quick reference for binding parameters to Bind()// -----------------------------------------------------------------------------//// Bound parameters are specified as arguments to Bind() and are passed to the// function. A callback with no parameters or no unbound parameters is called a// Closure (base::Callback<void(void)> and base::Closure are the same thing).//// PASSING PARAMETERS OWNED BY THE CALLBACK// //// void Foo(int* arg) { cout << *arg << endl; }// int* pn = new int(1);// 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 scoped_ptr// 如果想只能运行一次,用scoped_ptr就最适合了,运行后自动设置指针为null,// 没有运行的话Callback销毁时跟着销毁scoped_ptr//// void TakesOwnership(scoped_ptr<Foo> arg) {}// scoped_ptr<Foo> f(new Foo);// // f becomes null during the following call.// base::Closure cb = base::Bind(&TakesOwnership, base::Passed(&f));//// Ownership of the parameter will be with the callback until the it is run,// when 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//// void TakesOneRef(scoped_refptr<Foo> arg) {}// scoped_refptr<Foo> f(new Foo)// 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.//// PASSING PARAMETERS BY REFERENCE//// void foo(int arg) { cout << arg << endl }// int n = 1;// base::Closure has_ref = base::Bind(&foo, base::ConstRef(n));// n = 2;// has_ref.Run(); // Prints "2"//// Normally parameters are copied in the closure. DANGER: ConstRef stores 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 Callback and Bind is heavily influenced by C++'s// tr1::function/tr1::bind, and by the "Google Callback" system used inside// Google.////// HOW THE IMPLEMENTATION WORKS://// There are three main components to the system:// 1) The Callback classes.// 2) The Bind() functions.// 3) The arguments wrappers (e.g., Unretained() and ConstRef()).//// 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. Each Callback specialization has a templated// constructor that takes an BindState<>*. In the context of the constructor,// the static type of this BindState<> pointer uniquely identifies the// function it is representing, all its bound parameters, and a Run() method// that is capable of invoking the target.//// Callback's constructor takes the 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 BindState<>* to a// BindStateBase*. This is safe as long as this BindStateBase pointer// is only used with the stored Run() pointer.//// To BindState<> objects are created inside the 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 an 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 Bind functions do the above using type-inference, and template// specializations.//// By default 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., Unretained(), and ConstRef()). 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, and the MaybeRefcount()// functions respectively to modify the behavior of Bind(). The Unwrap()// and MaybeRefcount() functions change behavior by doing partial// specialization based on whether or not a parameter is a wrapper type.//// ConstRef() is similar to tr1::cref. Unretained() is specific to Chromium.////// WHY NOT TR1 FUNCTION/BIND?//// Direct use of tr1::function and tr1::bind was considered, but ultimately// rejected because of the number of copy constructors invocations involved// in the binding of arguments during construction, and the forwarding of// arguments during invocation. These copies will no longer be an issue in// C++0x because C++0x will support rvalue reference allowing for the compiler// to avoid these copies. However, waiting for C++0x is not an option.//// Measured with valgrind on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5), the// tr1::bind call itself will invoke a non-trivial copy constructor three times// for each bound parameter. Also, each when passing a tr1::function, each// bound argument will be copied again.//// In addition to the copies taken at binding and invocation, copying a// tr1::function causes a copy to be made of all the bound parameters and// state.//// Furthermore, in Chromium, it is desirable for the Callback to take a// reference on a target object when representing a class method call. This// is not supported by tr1.//// Lastly, tr1::function and tr1::bind has a more general and flexible API.// This includes things like argument reordering by use of// tr1::bind::placeholder, support for non-const reference parameters, and some// limited amount of subtyping of the tr1::function object (e.g.,// tr1::function<int(int)> is convertible to tr1::function<void(int)>).//// These are not features that are required in Chromium. Some of them, such as// allowing for reference parameters, and subtyping of functions, may actually// become a source of errors. Removing support for these features actually// allows for a simpler implementation, and a terser Currying API.////// WHY NOT GOOGLE CALLBACKS?//// The Google callback system also does not support refcounting. Furthermore,// its implementation has a number of strange edge cases with respect to type// conversion of its arguments. In particular, the argument's constness must// at times match exactly the function signature, or the type-inference might// break. Given the above, writing a custom solution was easier.////// MISSING FUNCTIONALITY// - Invoking the return of Bind. Bind(&foo).Run() does not work;// - Binding arrays to functions that take a non-const pointer.// Example:// void Foo(const char* ptr);// void Bar(char* ptr);// Bind(&Foo, "test");// Bind(&Bar, "test"); // This fails because ptr is not const.
- chromium Callback 部分翻译
- 【Android翻译】KeyEvent.Callback
- Chromium Base学习笔记 —— Callback
- Chromium CC部分浅析(一)
- Chromium的智能指针/引用计数/Callback/Bind
- [Android翻译]Acitivty中的KeyEvent.Callback接口
- Chromium CC部分浅析(二)
- Chromium CC部分浅析(三)
- RAS SDK部分翻译
- RFC4226 的部分翻译
- OpenBravo财务报表部分翻译
- UIView中文部分翻译
- iw 原文部分翻译
- RT3070AP 部分翻译文档
- UIScroview 部分翻译
- Twain协议部分翻译
- DDR2 说明书部分翻译
- flexbus部分翻译
- 版本管理器的发展史
- MFC学习第二节:在窗口中输出0-100的十行十列数字
- 细胞编程:控制你的身体
- 数据仓库维度模型粒度提升情况浅析
- 字符串的格式化输入与输出
- chromium Callback 部分翻译
- zoj1489 hdu 1395 (数论)
- javascript中的单例模式
- 提升火狐的上网速度
- IOS之通讯录ABAddressBook
- c++排序和去除重复的算法
- 使用sencha cmd 进行开发,测试和生产prod.
- Google Buffer代码生成工具
- 博弈知识汇总