[英]unique_ptr<> v shared_ptr<> in regards to destruction policy
我一直在教自己作為C ++ 0x一部分的智能指針,並且遇到了一些與我不一致的東西。 具體來說,如何處理unique_ptr <>和shared_ptr <>的銷毀策略。
對於unique_ptr <>,您可以專門化std :: default_delete <>,從那時起,除非您明確請求其他銷毀策略,否則將使用新的默認值。
考慮以下:
struct some_c_type;
some_c_type *construct_some_c_type();
void destruct_some_c_type(some_c_type *);
namespace std {
template <> struct default_delete<some_c_type> {
void operator()(some_c_type *ptr) {
destruct_some_c_type(ptr);
}
};
}
現在,一旦到位,unique_ptr <>將默認使用適當的銷毀策略:
// Because of the specialization, this will use destruct_some_c_type
std::unique_ptr<some_c_type> var(construct_some_c_type());
現在將其與shared_ptr <>進行比較。 使用shared_ptr <>,您需要顯式請求相應的銷毀策略,或者默認使用operator delete:
// error, will use operator delete
std::shared_ptr<some_c_type> var(construct_some_c_type());
// correct, must explicitly request the destruction policy
std::shared_ptr<some_c_type> var(construct_some_c_type(),
std::default_delete<some_c_type>());
兩個問題。
PS我關心這個的原因是我的公司做了很多混合的C和C ++編程。 C ++代碼通常需要使用C風格的對象,因此指定不同的默認銷毀策略的簡便性對我來說非常重要。
我認為這個問題歸結為為什么std :: shared_ptr沒有關聯的刪除器(在這種情況下它只是調用delete
)而不是默認構造一個std::default_delete
。 (不知道。如果意圖是default_delete
用於專門化,那么人們會期望它由shared_ptr
。)
否則就需要權衡利弊。
最好有更少的模板參數。 Boost的參考文獻提到,這允許工廠更改分配方案,而不會影響工廠用戶。
另一方面, unique_ptr
應該是非常輕量級的。 如果它不是類型的一部分(GCC使用元組,其中無成員對象不占用內存空間),那么如何以零空間開銷(如果沒有成員的仿函數)存儲刪除器?
主觀上,我認為我更喜歡:
unique_ptr<FILE, FCloser> f(fopen(x, y));
至
unique_ptr<FILE> f(fopen(x, y)); //default_delete<FILE> has been specialized
在第一種情況下,沒有什么可猜測的。 如果資源不是來自new
或new[]
,則必須明確給出刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.