4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Angus Leeming
9 * A templated class that can serve as a pointer to an object, with the
10 * property that when the copied_ptr is copied, it creates its own copy
11 * of the object pointed to as well.
13 * The implementation was based originally on Yonat Sharon's copied_ptr templated
14 * class, as described at http://ootips.org/yonat/, but has evolved toward's
15 * Herb Sutter's HolderPtr, as described at http://www.gotw.ca/gotw/062.htm.
16 * (Note, HolderPtr became ValuePtr in his book, More Exceptional C++.)
18 * Warning: if the class stores 'Base * ptr_', but the actual object pointed to
19 * belongs to a derived class, then you must specialise memory_traits<Base> so that
20 * its clone and destroy member functions do the right thing. Otherwise, you'll
21 * end up slicing the data.
31 struct memory_traits {
32 static T * clone(T const * ptr) { return new T(*ptr); }
33 static void destroy(T * ptr) { delete ptr; }
37 template <typename T, typename Traits=memory_traits<T> >
40 explicit copied_ptr(T * = 0);
41 copied_ptr(copied_ptr const &);
43 copied_ptr & operator=(copied_ptr const &);
45 T & operator*() const;
46 T * operator->() const;
54 template <typename T, typename Traits>
55 copied_ptr<T, Traits>::copied_ptr(T * p)
60 template <typename T, typename Traits>
61 copied_ptr<T, Traits>::copied_ptr(copied_ptr const & other)
62 : ptr_(other.ptr_ ? Traits::clone(other.ptr_) : 0)
66 template <typename T, typename Traits>
67 copied_ptr<T, Traits>::~copied_ptr()
69 Traits::destroy(ptr_);
73 template <typename T, typename Traits>
74 copied_ptr<T, Traits> & copied_ptr<T, Traits>::operator=(copied_ptr const & other)
77 copied_ptr temp(other);
78 std::swap(ptr_, temp.ptr_);
84 template <typename T, typename Traits>
85 T & copied_ptr<T, Traits>::operator*() const
91 template <typename T, typename Traits>
92 T * copied_ptr<T, Traits>::operator->() const
98 template <typename T, typename Traits>
99 T * copied_ptr<T, Traits>::get() const
104 } // namespace support
107 #endif // NOT COPIED_PTR_H