NAO documentation
|
C++ Libraries
|
index
libqi
1.14
Main Page
Related Pages
Modules
Namespaces
Classes
Files
Examples
File List
File Members
All
Classes
Namespaces
Files
Functions
Variables
Typedefs
Enumerations
Enumerator
Groups
Pages
qi
shared_ptr.hpp
1
/*
2
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
3
* Use of this source code is governed by a BSD-style license that can be
4
* found in the COPYING file.
5
*/
6
7
#pragma once
8
9
#ifndef _LIBQI_QI_SHARED_PTR_HPP_
10
#define _LIBQI_QI_SHARED_PTR_HPP_
11
12
#include <qi/atomic.hpp>
13
#include <
qi/log.hpp
>
14
15
namespace
qi
16
{
17
template
<
typename
T>
18
class
SharedPtr
19
{
20
public
:
21
SharedPtr
(T *ptr)
22
: _ptr(ptr)
23
, _refcount(
new
qi::atomic<long>
(1))
24
{
25
}
26
27
~
SharedPtr
()
28
{
29
if
(--(*_refcount) == 0)
30
{
31
delete
_ptr;
32
delete
_refcount;
33
}
34
}
35
36
SharedPtr
(
const
SharedPtr<T>
&sp)
37
{
38
/*
39
* Note that this line is racy.
40
* If someone is deleting _refcount,
41
* it cannot be used below.
42
*/
43
if
(++(*_refcount) != 1)
44
{
45
_ptr = sp._ptr;
46
}
47
else
48
{
49
qiLogDebug
(
"qi.log.shared_ptr"
)
50
<<
"tried to copy a shared pointer targeted for deletion"
51
<< std::endl;
52
}
53
}
54
55
SharedPtr
& operator=(
SharedPtr<T>
&sp)
56
{
57
// release the current pointer
58
if
(--(*_refcount) == 0)
59
{
60
delete
_ptr;
61
delete
_refcount;
62
}
63
_ptr = sp._ptr;
64
_refcount = sp._refcount;
65
}
66
67
T &operator*()
const
68
{
69
return
*_ptr;
70
}
71
72
T *operator->()
const
73
{
74
return
_ptr;
75
}
76
77
private
:
78
T *_ptr;
79
qi::atomic<long>
*_refcount;
80
};
81
}
82
83
#endif // _LIBQI_QI_SHARED_PTR_HPP_
Copyright Aldebaran Robotics