C++核心准则CP.32:使用shared_ptr在无关线程之间共享所有权
CP.32: To share ownership between unrelated threads use shared_ptr
CP.32:使用shared_ptr在无关线程之间共享所有权
Reason(原因)
If threads are unrelated (that is, not known to be in the same scope or one within the lifetime of the other) and they need to share free store memory that needs to be deleted, a shared_ptr (or equivalent) is the only safe way to ensure proper deletion.
如果线程之间没有关联(即,无法断定处于相同的作用域,或者一个线程处于另一个线程的生命周期中)而且共享需要删除的自由存贮内存,share_ptr(或等价物)是可以保证安全、正确地销毁内存的唯一方法。
Example(示例)
???
Note(注意)
A static object (e.g. a global) can be shared because it is not owned in the sense that some thread is responsible for its deletion.
没有任何线程有责任销毁静态对象(例如全局变量),从这个角度来讲静态对象是没有所有者的。因此可以说静态变量是可以共享的。
An object on free store that is never to be deleted can be shared.
存在于永远不会被销毁的自由存储上的对象可以共享。
An object owned by one thread can be safely shared with another as long as that second thread doesn't outlive the owner.
只要第二个线程的生命期间没有长于所有者线程,那么一个线程拥有的对象就可以安全的分享给第二个线程。
Enforcement(实施建议)
???
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp31-pass-small-amounts-of-data-between-threads-by-value-rather-than-by-reference-or-pointer
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!