Fixed compile problems on gcc 2.95.x
[pwlib.git] / include / ptlib / psharedptr.h
blobfb887c5dc5dc858186ba5b5af4ff9490f32bf558
1 /*
2 * psharedptr.h
4 * SharedPtr template
6 * Portable Windows Library
8 * Copyright (C) 2004 Post Increment
10 * The contents of this file are subject to the Mozilla Public License
11 * Version 1.0 (the "License"); you may not use this file except in
12 * compliance with the License. You may obtain a copy of the License at
13 * http://www.mozilla.org/MPL/
15 * Software distributed under the License is distributed on an "AS IS"
16 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
17 * the License for the specific language governing rights and limitations
18 * under the License.
20 * The Original Code is Portable Windows Library.
22 * The Initial Developer of the Original Code is Post Increment
24 * Contributor(s): ______________________________________.
26 * $Log$
27 * Revision 1.3 2004/10/21 09:20:33 csoutheren
28 * Fixed compile problems on gcc 2.95.x
30 * Revision 1.2 2004/10/01 08:08:50 csoutheren
31 * Added Reset and auto_ptr conversions
33 * Revision 1.1 2004/10/01 07:17:18 csoutheren
34 * Added PSharedptr class
38 #ifndef _PSHAREDPTR_H
39 #define _PSHAREDPTR_H
41 #ifdef P_USE_PRAGMA
42 #pragma interface
43 #endif
45 #include <ptlib.h>
46 #include <memory>
48 /**
50 * These templates implement an pointner class with an integral reference count
51 * based on the PContainer base class. This allows the easy creation of an
52 * a reference counted ptr that will autodestruct when the last reference
53 * goes out of scope.
56 template <class T>
57 class PSharedPtr : public PContainer
59 PCLASSINFO(PSharedPtr, PContainer);
60 public:
61 typedef T element_type;
63 PSharedPtr(element_type * _ptr = NULL)
64 { ptr = _ptr; }
66 PSharedPtr(const PSharedPtr & c)
67 : PContainer(c)
68 { CopyContents(c); }
70 PSharedPtr(std::auto_ptr<element_type> & v)
71 { ptr = v.release(); }
73 PSharedPtr & operator=(const PSharedPtr & c)
74 { AssignContents(c); return *this; }
76 virtual ~PSharedPtr()
77 { Destruct(); }
79 virtual BOOL MakeUnique()
80 { if (PContainer::MakeUnique()) return TRUE; CloneContents(this); return FALSE; }
82 BOOL SetSize(PINDEX)
83 { return false; }
85 T * Get() const
86 { return ptr; }
88 void Reset() const
89 { AssignContents(PSharedPtr()); }
91 T & operator*() const
92 { return *ptr; }
94 T * operator->() const
95 { return ptr; }
98 protected:
99 PSharedPtr(int dummy, const PSharedPtr * c)
100 : PContainer(dummy, c)
101 { CloneContents(c); }
103 void AssignContents(const PContainer & c)
104 { PContainer::AssignContents(c); CopyContents((const PSharedPtr &)c); }
106 void DestroyContents()
107 { delete(ptr); }
109 void CloneContents(const PContainer * src)
110 { ptr = new element_type(*((const PSharedPtr *)src)->ptr); }
112 void CopyContents(const PContainer & c)
113 { ptr = ((const PSharedPtr &)c).ptr; }
115 protected:
116 T * ptr;
119 #endif // _PSHAREDPTR_H