天天看點

C++核心準則邊譯邊學-F.27 使用shared_ptr(T)共享所有權

F.27: Use a ​

​shared_ptr<T>​

​ to share ownership

F.27 使用shared_ptr<T>共享所有權

Reason(原因)

Using ​

​std::shared_ptr​

​ is the standard way to represent shared ownership. That is, the last owner deletes the object.

使用std::shared_ptr是表現所有權共享的标準方式。使用這種方式時,最後一個所有者負責銷毀對象。

Example(示例)

shared_ptr<const Image> im { read_image(somewhere) };
std::thread t0 {shade, args0, top_left, im};std::thread t1 {shade, args1, top_right, im};std::thread t2 {shade, args2, bottom_left, im};std::thread t3 {shade, args3, bottom_right, im};
// detach threads// last thread to finish deletes the image      

譯者注:代碼首先構造了一個Image對象并使用shared_ptr管理。然後将它們傳遞個4個線程共享這個對象。這段代碼會啟動四個線程,然後(應該)退出im的作用域。當所有線程結束時,最後一個結束的線程負責銷毀Image對象。

Note(注意)

Prefer a ​

​unique_ptr​

​​ over a ​

​shared_ptr​

​​ if there is never more than one owner at a time.​

​shared_ptr​

​ is for shared ownership.

Note that pervasive use of ​

​shared_ptr​

​​ has a cost (atomic operations on the ​

​shared_ptr​

​'s reference count have a measurable aggregate cost).

如果同一時刻永遠不會有多于一個所有者的話,unique_ptr比shared_ptr更合适。

Alternative(可選方式)

Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completed.

讓一個對象管理共享對象(例如範圍對象)并且當所有使用者都結束使用時(最好是隐式)銷毀該(共享)對象。

Enforcement(實施建議)

(Not enforceable) This is a too complex pattern to reliably detect.

(不可執行)模式過于複雜以至于無法可靠地檢查。

繼續閱讀