
"Preston A. Elder" <prez@neuromancy.net> wrote in message news:<dp8ak1$u33$1@sea.gmane.org>...
Hey,
What does everyone think of a new smart pointer called deep_ptr.
This pointer would hold a unique pointer (only one copy at a time), but provide convenient syntax to have a deep copy of the underlying data on an operator= call.
A sample implementation would be something like:
template<typename T> class deep_ptr { typedef deep_ptr<T> this_type;
public: typedef T element_type; typedef T value_type; typedef T * pointer; typedef T & reference;
deep_ptr() : px(NULL) {} deep_ptr(T * ptr) : px(ptr) {} deep_ptr(deep_ptr const & in) : px(new T(*in.px)) {} deep_ptr &operator=(deep_ptr const & in) { delete px; px = new T(*in.px); } ~deep_ptr() { delete px; }
void reset() { this_type().swap(*this); }
template<typename U> void reset(U * p) { BOOST_ASSERT(p == 0 || p != px); this_type(p).swap(*this); }
reference operator* () const { BOOST_ASSERT(px != 0); return *px; }
T * operator->() const { BOOST_ASSERT(px != 0); return px; }
T * get() const { return px; }
operator bool () const { return px != 0; }
bool operator! () const { return px == 0; }
void swap(deep_ptr<T> & other) { std::swap(px, other.px); }
private: T *px; };
template<typename T, typename U> inline bool operator==(deep_ptr<T> const & a, deep_ptr<U> const & b) { return a.get() == b.get(); }
template<typename T, typename U> inline bool operator!=(deep_ptr<T> const & a, deep_ptr<U> const & b) { return a.get() != b.get(); }
template<typename T, typename U> inline bool operator<(deep_ptr<T> const & a, deep_ptr<U> const & b) { return a.get() < b.get(); }
template<class T> inline void swap(deep_ptr<T> & a, deep_ptr<T> & b) { a.swap(b); }
This way, as I said, each copy would have its own version of the data, but in a class that uses it, you would not then have to write your own operator= for that class to handle the deep copy, you just make it use a deep_ptr instead of a regular pointer.
I'll admit, its simply a case of adding syntactical sugar, but I could see how this would become extremely useful :)
-- PreZ :)
I've previously suggested a similar class. Check out the following links: http://code.axter.com/copy_ptr.h (Deep copy clone (sole owner ship) pointer) http://code.axter.com/cow_ptr.h (Deep copy COW smart pointer Be aware, that your deep_ptr class will not work correctly using an abstract pointer. The copy_ptr and cow_ptr will clone (deep copy) the type pass to the constructor. In order for your deep_ptr to work correctly, it needs to either capture the type on the constructor and then save it, or implement a clone() function requirement for the target type.