brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 1 | #include <memory> |
| 2 | |
| 3 | namespace aos { |
| 4 | |
| 5 | namespace { |
| 6 | |
brians | da7756f | 2013-02-27 04:19:33 +0000 | [diff] [blame] | 7 | // Written as a functor so that it doesn't have to get passed to |
| 8 | // std::unique_ptr's constructor as an argument. |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 9 | template<typename T, void(*function)(T *)> |
brians | da7756f | 2013-02-27 04:19:33 +0000 | [diff] [blame] | 10 | class const_wrap { |
| 11 | public: |
| 12 | void operator()(const T *ptr) { |
| 13 | function(const_cast<T *>(ptr)); |
| 14 | } |
| 15 | }; |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 16 | |
| 17 | // Wrapper function to deal with the differences between C and C++ (C++ doesn't |
| 18 | // automatically convert T* to void* like C). |
| 19 | template<typename T> |
| 20 | void free_type(T *ptr) { ::free(reinterpret_cast<void *>(ptr)); } |
| 21 | |
| 22 | } // namespace |
| 23 | |
| 24 | // A std::unique_ptr that should get freed with a C-style free function |
| 25 | // (free(2) by default). |
brians | da7756f | 2013-02-27 04:19:33 +0000 | [diff] [blame] | 26 | template<typename T, void(*function)(T *) = free_type<T>> |
| 27 | class unique_c_ptr : public std::unique_ptr<T, const_wrap<T, function>> { |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 28 | public: |
brians | da7756f | 2013-02-27 04:19:33 +0000 | [diff] [blame] | 29 | unique_c_ptr(T *value) : std::unique_ptr<T, const_wrap<T, function>>(value) {} |
| 30 | |
| 31 | // perfect forwarding of these 2 to make unique_ptr work |
| 32 | template<typename... Args> |
| 33 | unique_c_ptr(Args&&... args) |
| 34 | : std::unique_ptr<T, const_wrap<T, function>>(std::forward<Args>(args)...) { |
| 35 | } |
| 36 | template<typename... Args> |
| 37 | unique_c_ptr<T, function> &operator=(Args&&... args) { |
| 38 | std::unique_ptr<T, const_wrap<T, function>>::operator=( |
| 39 | std::forward<Args>(args)...); |
| 40 | return *this; |
| 41 | } |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 42 | }; |
| 43 | |
| 44 | } // namespace aos |