posttask parameter Decision tree
How to pass a bound object
The official explanation is always the most authoritative, there are questions to see here or directly read the instructions in the code: BIND_HELPERS.H.
| method of transmitting value |
Description |
| This or the object pointer |
If the object itself is a refcountedthreadsafe, there is no problem. If it is a bare pointer, you should try to avoid it unless you can ensure that it is thread safe. |
| base::unretained |
Note: The premise of using this is that there are other synchronization mechanisms that guarantee the life cycle of the object.
- If there are other synchronization mechanisms that guarantee the life cycle of an object, you can use unretained () to pass non-reference count objects.
- If the object is a non-reference count, it can be encapsulated using unretained ().
|
| base::owned |
If it is a temporary object, or if the object may leak after the task is completed, you can use owned, which is represented by the task Hold the ownership of the object and, at the end, refactor it. |
| Base::P |
If you want to execute a task that requires an incoming scoped pointer, you can use it to convert, which also avoids copying, but is similar to move semantics. |
| Base::constref |
Like a constant reference, you do not want a copy of the bind process to be used. |
| Base::ignoreresult |
If the task is to invoke a method with a return value, and you do not care about the return value, you can use Ignoreresult to pass in the object pointer. |
Discussion: Why avoid reference counting?
Why avoid reference counting if it is not always easy to use objects with reference counts?
Explanation in the Chromium smart pointer Guide:
- reference-counted objects make it difficult to understand ownership and destruction order, especially when multiple thread S is involved. There is almost always another-to design your object hierarchy to avoid refcounting. Avoiding refcounting in multithreaded situations are usually easier if you restrict each class to operating on just one THR EAD, and use Posttask () and the As to proxy calls to the correct thread. Base::bind (), Weakptr, and other tools make it possible to automatically cancel calls to such a object when it dies. Note that too much of We existing code uses refcounting, so just because do see existing code doing it does not mean it ' s the right solution. (Bonus points if you ' re able to clean up such cases.)
Also refer to: Use smart pointers with caution.
Reference
More complete explanations of callback and bind for object ownership
[Chromium] How to safely use the Posttask