Reputation: 1
auto_ptr doesn't support custom deleter and tr1 shared_ptr
is not a good option for me.
Are there any good options before c11 for unique_ptr
/ auto_ptr
look alike with custom deleter?
Upvotes: 0
Views: 464
Reputation: 73206
A unique_ptr
implementation without the move semantics of C++11 (and beyond) is a bit tricky, but if you could emulate move semantics, you could go forward with an implementation of similar semantics as that of std::unique_ptr
.
Boost provided this very implementation for C++03, as part of the Boost.Move library:
What is Boost.Move?
Rvalue references are a major C++0x feature, enabling move semantics for C++ values. However, we don't need C++0x compilers to take advantage of move semanatics. Boost.Move emulates C++0x move semantics in C++03 compilers and allows writing portable code that works optimally in C++03 and C++0x compilers.
Specifically, from Boost 1.57 and onwards, providing boost/move/unique_ptr.hpp
//!\file //! Describes the smart pointer unique_ptr, a drop-in replacement for std::unique_ptr, //! usable also from C++03 compilers. //! //! Main differences from std::unique_ptr to avoid heavy dependencies, //! specially in C++03 compilers: //! - <tt>operator < </tt> uses pointer <tt>operator < </tt>instead of <tt>std::less<common_type></tt>. //! This avoids dependencies on <tt>std::common_type</tt> and <tt>std::less</tt> //! (<tt><type_traits>/<functional></tt> headers. In C++03 this avoid pulling Boost.Typeof and other //! cascading dependencies. As in all Boost platforms <tt>operator <</tt> on raw pointers and //! other smart pointers provides strict weak ordering in practice this should not be a problem for users. //! - assignable from literal 0 for compilers without nullptr //! - <tt>unique_ptr<T[]></tt> is constructible and assignable from <tt>unique_ptr<U[]></tt> if //! cv-less T and cv-less U are the same type and T is more CV qualified than U.
which allows providing an associated non-default deleter to the unique_ptr
:
//! A unique pointer is an object that owns another object and //! manages that other object through a pointer. //! //! ... //! //! \tparam T Provides the type of the stored pointer. //! \tparam D The deleter type: //! - The default type for the template parameter D is default_delete. A client-supplied template argument //! D shall be a function object type, lvalue-reference to function, or lvalue-reference to function object type //! for which, given a value d of type D and a value ptr of type unique_ptr<T, D>::pointer, the expression //! d(ptr) is valid and has the effect of disposing of the pointer as appropriate for that deleter. //! - If the deleter's type D is not a reference type, D shall satisfy the requirements of Destructible. //! - If the type <tt>remove_reference<D>::type::pointer</tt> exists, it shall satisfy the requirements of NullablePointer. template <class T, class D = default_delete<T> > class unique_ptr { /* ... */ }
Upvotes: 0