Arduino Libraries
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
shared_ptr.hpp
Go to the documentation of this file.
1 // Author: Mario S. Könz <mskoenz@gmx.net>
2 // Date: 14.11.2013 00:38:16 CET
3 // File: shared_ptr.hpp
4 
5 /* This program is free software. It comes without any warranty, to
6  * the extent permitted by applicable law. You can redistribute it
7  * and/or modify it under the terms of the Do What The Fuck You Want
8  * To Public License, Version 2, as published by Sam Hocevar. See
9  * http://www.wtfpl.net/ or COPYING for more details. */
10 
11 #ifndef __SHARED_PTR_HEADER
12 #define __SHARED_PTR_HEADER
13 
14 namespace ustd {
15  template<typename T>
16  class shared_ptr {
17  void incr() {
18  ++(*count_);
19  }
20  void decr() {
21  --(*count_);
22  }
23  public:
24  typedef T element_type;
25 
26  //------------------- ctor -------------------
27  explicit shared_ptr(T * ptr = NULL): ptr_(ptr) {
28  count_ = new uint8_t(0);
29  ASSERT(count_ != NULL)
30  incr();
31  }
32  shared_ptr(shared_ptr const & rhs): ptr_(rhs.ptr_), count_(rhs.count_) {
33  incr();
34  }
35  //------------------- dtor -------------------
37  if(ptr_ == NULL) {
38  decr();
39  return;
40  }
41  if(*count_ == 1) {
42  delete ptr_;
43  delete count_;
44  } else {
45  ptr_ = NULL;
46  decr();
47  }
48  }
49  //------------------- assign -------------------
50  shared_ptr & operator=(shared_ptr const & rhs) {
51  if(ptr_ != rhs.ptr_) {
52  if(ptr_ != NULL) {
53  if(*count_ == 1) {
54  delete ptr_;
55  delete count_;
56  }
57  else
58  decr();
59  }
60 
61  ptr_ = rhs.ptr_;
62  count_ = rhs.count_;
63  incr();
64  }
65  return (*this);
66  }
67  //------------------- deref -------------------
69  return ptr_;
70  }
71  element_type & operator*() const {
72  return *ptr_;
73  }
74  //------------------- compare -------------------
75  //~ bool operator==(T * ptr) const {
76  //~ return ptr == ptr_;
77  //~ }
78  //~ bool operator==(shared_ptr const & arg) const {
79  //~ return arg.prt_ == ptr_;
80  //~ }
81  bool operator!=(T * ptr) const {
82  return ptr != ptr_;
83  }
84  bool operator!=(shared_ptr const & arg) const {
85  return arg.prt_ != ptr_;
86  }
87  private:
88  element_type * ptr_;
89  uint8_t * count_;
90  };
91 }//end namespace ustd
92 #endif //__SHARED_PTR_HEADER
element_type * operator->() const
Definition: shared_ptr.hpp:68
bool operator!=(T *ptr) const
Definition: shared_ptr.hpp:81
shared_ptr(T *ptr=NULL)
Definition: shared_ptr.hpp:27
Definition: shared_ptr.hpp:16
T element_type
Definition: shared_ptr.hpp:24
bool operator!=(shared_ptr const &arg) const
Definition: shared_ptr.hpp:84
element_type & operator*() const
Definition: shared_ptr.hpp:71
shared_ptr & operator=(shared_ptr const &rhs)
Definition: shared_ptr.hpp:50
~shared_ptr()
Definition: shared_ptr.hpp:36
#define ASSERT(exp)
Definition: ard_assert.hpp:33
shared_ptr(shared_ptr const &rhs)
Definition: shared_ptr.hpp:32