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?
c ++ c ++ 11 rule-of-zero
Barry
source share