]> git.lyx.org Git - lyx.git/blob - src/support/copied_ptr.h
Add copied_ptr.h to the repository too.
[lyx.git] / src / support / copied_ptr.h
1 // -*- C++ -*-
2 /**
3  * \file copied_ptr.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Yonat Sharon http://ootips.org/yonat/
8  *
9  * simple copy-on-create/assign pointer.
10  *
11  * Note: If the actual object pointed to belongs to a derived class,
12  * then copied_ptr will not create a copy of the derived class object,
13  * but a new base class object.
14  * If you want to use a polymorphic copy-on-assign pointer, use
15  * cloned_ptr.
16  */
17
18 #ifndef COPIED_PTR_H
19 #define COPIED_PTR_H
20
21 namespace lyx {
22 namespace support {
23
24 template <typename T>
25 class copied_ptr {
26 public:
27         explicit copied_ptr(T * = 0);
28         ~copied_ptr();
29         copied_ptr(copied_ptr const &);
30         copied_ptr & operator=(copied_ptr const &);
31
32         T & operator*() const;
33         T * operator->() const;
34         T * get() const;
35
36 private:
37         T * ptr_;
38         void copy(copied_ptr const &);
39 };
40
41
42 template <typename T>
43 copied_ptr<T>::copied_ptr(T * p)
44         : ptr_(p)
45 {}
46
47
48 template <typename T>
49 copied_ptr<T>::~copied_ptr()
50 {
51         delete ptr_;
52 }
53
54
55 template <typename T>
56 copied_ptr<T>::copied_ptr(copied_ptr const & other)
57 {
58         copy(other.get());
59 }
60
61
62 template <typename T>
63 copied_ptr<T> & copied_ptr<T>::operator=(copied_ptr const & other)
64 {
65         if (&other != this) {
66                 delete ptr_;
67                 copy(other);
68         }
69         return *this;
70 }
71
72
73 template <typename T>
74 T & copied_ptr<T>::operator*() const
75 {
76         return *ptr_;
77 }
78
79
80 template <typename T>
81 T * copied_ptr<T>::operator->() const
82 {
83         return ptr_;
84 }
85
86
87 template <typename T>
88 T * copied_ptr<T>::get() const
89 {
90         return ptr_;
91 }
92
93
94 template <typename T>
95 void copied_ptr<T>::copy(copied_ptr const & other)
96 {
97         ptr_ = other.ptr_ ? new T(*other.ptr_) : 0;
98 }
99
100 } // namespace support
101 } // namespace lyx
102
103 #endif // NOT COPIED_PTR_H