我一直在自学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>());
两个问题。
- 我是否正确,每次使用shared_ptr<>都需要指定销毁策略,还是我漏掉了什么?
- 如果我没有漏掉什么,有什么想法可以解释为什么这两者不同?
P.S. 我关心这个问题的原因是我们公司进行大量混合C和C++编程。C++代码经常需要使用C风格的对象,因此指定不同的默认销毁策略的便利性对我来说非常重要。
std::default_delete<some_c_type>()
吗?另外,顺便说一下,除非在 C++0x 中已经修复了,否则这三个都是棘手的。 - GManNickG