的unique_ptr<> v shared_ptr<>关于销毁政策

时间:2010-02-19 23:53:20

标签: c++ c++11

我一直在教自己作为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&lt;&gt;默认情况下将使用适当的销毁政策:

// Because of the specialization, this will use destruct_some_c_type
std::unique_ptr<some_c_type> var(construct_some_c_type());

现在将此与shared_ptr&lt;&gt;进行比较。使用shared_ptr&lt;&gt;,您需要显式请求相应的销毁策略,或者默认使用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>());

两个问题。

  1. 我是否更正了shared_ptr&lt;&gt;要求每次使用销毁政策时指定销毁政策,还是我遗漏了什么?
  2. 如果我没有遗漏某些东西,任何想法为什么两者都不同?
  3. P.S。我关心这个的原因是我公司做了很多混合的C和C ++编程。 C ++代码通常需要使用C风格的对象,因此指定不同的默认销毁策略非常容易。

1 个答案:

答案 0 :(得分:4)

我认为问题归结为为什么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

在第一种情况下,没有什么可猜的。如果资源不是来自newnew[],则必须明确指定删除者。

相关问题