unique_ptr,自定义删除和零规则

Bar*_*rry 7 c++ c++11 rule-of-zero

我正在编写一个使用C接口创建的两个对象的类.对象看起来像:

typedef struct... foo_t;
foo_t* create_foo(int, double, whatever );
void delete_foo(foo_t* );
Run Code Online (Sandbox Code Playgroud)

(同样如此bar_t).因为C++ 11,我想将它们包装在智能指针中,所以我不必编写任何特殊方法.该类将拥有这两个对象的唯一所有权,因此unique_ptr逻辑上有意义......但我仍然需要编写一个构造函数:

template <typename T>
using unique_ptr_deleter = std::unique_ptr<T, void(*)(T*)>;

struct MyClass {
     unique_ptr_deleter<foo_t> foo_;
     unique_ptr_deleter<bar_t> bar_;

     MyClass()
         : foo_{nullptr, delete_foo}
         , bar_{nullptr, delete_bar}
     { }

     ~MyClass() = default;

     void create(int x, double y, whatever z) {
         foo_.reset(create_foo(x, y, z));
         bar_.reset(create_bar(x, y, z));
};
Run Code Online (Sandbox Code Playgroud)

另一方面shared_ptr,我不必编写构造函数,或使用类型别名,因为我可以直接delete_foo进入reset()- 虽然这会使我的可MyClass复制,我不希望这样.

MyClass使用unique_ptr语义编写并仍然遵守Zero规则的正确方法是什么?

Mik*_*our 8

您的类不需要声明析构函数(无论您是否声明默认实现,它都将获得正确的默认实现),因此仍然遵守"零规则".

但是,您可以通过使删除函数对象而不是指针来改进这一点:

template <typename T> struct deleter;
template <> struct deleter<foo_t> {
    void operator()(foo_t * foo){delete_foo(foo);}
};
template <> struct deleter<bar_t> {
    void operator()(bar_t * bar){delete_bar(bar);}
};

template <typename T>
using unique_ptr_deleter = std::unique_ptr<T, deleter<T>>;
Run Code Online (Sandbox Code Playgroud)

这有一些好处:

  • unique_ptr并不需要存储一个额外的指针
  • 删除函数可以直接调用,而不是通过指针调用
  • 你不需要写一个构造函数; 默认构造函数将做正确的事情.