Unique_ptr, custom div and zero rule

I am writing a class that uses two objects created using the C interface. The objects look like this:

typedef struct... foo_t; foo_t* create_foo(int, double, whatever ); void delete_foo(foo_t* ); 

(similar for bar_t ). Since C ++ 11, I want to wrap them in a smart pointer, so I don't need to write any special methods. The class will have a unique ownership of two objects, so unique_ptr logically makes sense ... but I still have to write a constructor:

 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)); }; 

On the flip side, with shared_ptr , I would not need to write a constructor or use a type alias, as I could just go to delete_foo in reset() - although that would make my MyClass Copy, and I don't want to.

What is the correct way to write MyClass using unique_ptr semantics and still stick to the null rule?

+7
c ++ c ++ 11 rule-of-zero
source share
1 answer

Your class should not declare a destructor (it will get the correct default implementation, regardless of whether you declare it by default), therefore it still respects the "Zero rule".

However, you can improve this by making objects of name objects, rather than pointers:

 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>>; 

This has several advantages:

  • unique_ptr no need to store an extra pointer
  • delete function can be called directly, and not through a pointer
  • You do not need to write a constructor; the default constructor will do everything right.
+8
source share

All Articles