C++核心準(zhǔn)則CP.32:使用shared_ptr在無(wú)關(guān)線(xiàn)程之間共享所有權(quán)

CP.32: To share ownership between unrelated?threads use shared_ptr
CP.32:使用shared_ptr在無(wú)關(guān)線(xiàn)程之間共享所有權(quán)
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.
如果線(xiàn)程之間沒(méi)有關(guān)聯(lián)(即,無(wú)法斷定處于相同的作用域,或者一個(gè)線(xiàn)程處于另一個(gè)線(xiàn)程的生命周期中)而且共享需要?jiǎng)h除的自由存貯內(nèi)存,share_ptr(或等價(jià)物)是可以保證安全、正確地銷(xiāo)毀內(nèi)存的唯一方法。
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.
沒(méi)有任何線(xiàn)程有責(zé)任銷(xiāo)毀靜態(tài)對(duì)象(例如全局變量),從這個(gè)角度來(lái)講靜態(tài)對(duì)象是沒(méi)有所有者的。因此可以說(shuō)靜態(tài)變量是可以共享的。
An object on free store that is never to be deleted can be shared.
存在于永遠(yuǎn)不會(huì)被銷(xiāo)毀的自由存儲(chǔ)上的對(duì)象可以共享。
An object owned by one thread can be safely shared with another as long as that second thread doesn't outlive the owner.
只要第二個(gè)線(xiàn)程的生命期間沒(méi)有長(zhǎng)于所有者線(xiàn)程,那么一個(gè)線(xiàn)程擁有的對(duì)象就可以安全的分享給第二個(gè)線(xiàn)程。
Enforcement(實(shí)施建議)
???
原文鏈接
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
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
