yat  0.21pre
SmartPtr.h
1 #ifndef _theplu_yat_utility_smart_ptr_
2 #define _theplu_yat_utility_smart_ptr_
3 
4 // $Id: SmartPtr.h 3992 2020-09-17 03:42:03Z peter $
5 
6 /*
7  Copyright (C) 2008 Jari Häkkinen, Peter Johansson
8  Copyright (C) 2012, 2014, 2020 Peter Johansson
9 
10  This file is part of the yat library, http://dev.thep.lu.se/yat
11 
12  The yat library is free software; you can redistribute it and/or
13  modify it under the terms of the GNU General Public License as
14  published by the Free Software Foundation; either version 3 of the
15  License, or (at your option) any later version.
16 
17  The yat library is distributed in the hope that it will be useful,
18  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20  General Public License for more details.
21 
22  You should have received a copy of the GNU General Public License
23  along with yat. If not, see <http://www.gnu.org/licenses/>.
24 */
25 
26 #include "yat_assert.h"
27 
28 namespace theplu {
29 namespace yat {
30 namespace utility {
31 
47  template<typename T>
48  class SmartPtr
49  {
50  public:
73  explicit SmartPtr(T* p=NULL, bool owner=true)
74  : pointee_(p)
75  {
76  if (owner)
77  ref_count_ = new unsigned int(1);
78  else
79  ref_count_ = NULL;
80  }
81 
85  SmartPtr(const SmartPtr& other)
86  : pointee_(other.pointee_), ref_count_(other.ref_count_)
87  {
88  if (ref_count_)
89  ++(*ref_count_);
90  }
91 
97  virtual ~SmartPtr()
98  {
99  detach();
100  }
101 
108  {
109  if (pointee_!=rhs.pointee_){
110  detach();
111  pointee_ = rhs.pointee_;
112  ref_count_= rhs.ref_count_;
113  if (ref_count_)
114  ++(*ref_count_);
115  }
116  return *this;
117  }
118 
122  T* operator->(void) const
123  {
124  return pointee_;
125  }
126 
130  T& operator*(void) const
131  {
132  return *pointee_;
133  }
134 
135  private:
136  T* pointee_;
137  unsigned int* ref_count_;
138 
139  void detach(void)
140  {
141  if (ref_count_)
142  if (!--(*ref_count_))
143  delete pointee_;
144  }
145  };
146 
147 }}} // of namespace utility, yat, and theplu
148 #endif
virtual ~SmartPtr()
Destructor.
Definition: SmartPtr.h:97
The Department of Theoretical Physics namespace as we define it.
SmartPtr(T *p=NULL, bool owner=true)
Constructor.
Definition: SmartPtr.h:73
SmartPtr(const SmartPtr &other)
Copy constructor.
Definition: SmartPtr.h:85
Definition: SmartPtr.h:48
T & operator*(void) const
Definition: SmartPtr.h:130
SmartPtr & operator=(const SmartPtr &rhs)
Definition: SmartPtr.h:107
T * operator->(void) const
Definition: SmartPtr.h:122

Generated on Wed Jan 25 2023 03:34:29 for yat by  doxygen 1.8.14