libqi-api  2.1.4.13
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
shared_ptr.hpp
Go to the documentation of this file.
1 #pragma once
2 /*
3  * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the COPYING file.
6  */
7 
8 
9 #ifndef _QI_SHARED_PTR_HPP_
10 #define _QI_SHARED_PTR_HPP_
11 
12 #include <qi/atomic.hpp>
13 #include <qi/log.hpp>
14 
15 namespace qi
16 {
18  template <typename T>
19  class SharedPtr
20  {
21  public:
23  SharedPtr(T *ptr)
24  : _ptr(ptr)
25  , _refcount(new qi::Atomic<int>(1))
26  {
27  }
28 
32  {
33  if (--(*_refcount) == 0)
34  {
35  delete _ptr;
36  delete _refcount;
37  }
38  }
39 
42  {
43  /*
44  * Note that this line is racy.
45  * If someone is deleting _refcount,
46  * it cannot be used below.
47  */
48  if (++(*sp._refcount) != 1)
49  {
50  _ptr = sp._ptr;
51  _refcount = sp._refcount;
52  }
53  else
54  {
55 
56  _ptr = 0;
57  _refcount = 0;
58  qiLogDebug("qi.log.shared_ptr")
59  << "tried to copy a shared pointer targeted for deletion"
60  << std::endl;
61  }
62  }
63 
67  {
68  // release the current pointer
69  if (--(*_refcount) == 0)
70  {
71  delete _ptr;
72  delete _refcount;
73  }
74  if (++(*sp._refcount) != 1)
75  {
76  _ptr = sp._ptr;
77  _refcount = sp._refcount;
78  }
79  else
80  {
81  qiLogDebug("qi.log.shared_ptr")
82  << "tried to copy a shared pointer targeted for deletion"
83  << std::endl;
84  }
85  return *this;
86  }
87 
89  T &operator*() const
90  {
91  return *_ptr;
92  }
93 
95  T *operator->() const
96  {
97  return _ptr;
98  }
99 
100  private:
101  T *_ptr;
102  qi::Atomic<int> *_refcount;
103  };
104 }
105 
106 #endif // _QI_SHARED_PTR_HPP_
~SharedPtr()
Destruct the shared pointer and the pointer if current SharedPtr is the last one to hold the pointer...
Definition: shared_ptr.hpp:31
T * operator->() const
Pointer accessor.
Definition: shared_ptr.hpp:95
SharedPtr(const SharedPtr< T > &sp)
Copy shared pointer.
Definition: shared_ptr.hpp:41
SharedPtr(T *ptr)
Initialization of the SharedPtr with the pointer it will manage.
Definition: shared_ptr.hpp:23
T & operator*() const
Value accessor.
Definition: shared_ptr.hpp:89
#define qiLogDebug(...)
Log in debug mode. This level is not shown by default.
Definition: log.hpp:38
Lightweight implementation of shared pointers.
Definition: shared_ptr.hpp:19
Atomic operations on integers.
Definition: atomic.hpp:88
SharedPtr & operator=(SharedPtr< T > &sp)
Link current SharedPtr to a new pointer. If old pointer was only held by the current SharedPtr...
Definition: shared_ptr.hpp:66
Convenient log macro.