[英]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.