1 : /*
2 : * Copyright (c) 2011 The Native Client Authors. All rights reserved.
3 : * Use of this source code is governed by a BSD-style license that can be
4 : * found in the LICENSE file.
5 : */
6 :
7 : #ifndef NATIVE_CLIENT_SRC_SHARED_PLATFORM_SCOPED_PTR_REFCOUNT_H_
8 : #define NATIVE_CLIENT_SRC_SHARED_PLATFORM_SCOPED_PTR_REFCOUNT_H_
9 :
10 : namespace nacl {
11 :
12 : template <typename RC>
13 : class scoped_ptr_refcount {
14 : public:
15 : // standard ctors
16 28 : explicit scoped_ptr_refcount(RC* p = NULL)
17 14 : : ptr_(p) {
18 28 : }
19 :
20 : // copy ctor
21 : scoped_ptr_refcount(scoped_ptr_refcount const& other) {
22 : ptr_ = other.ptr_->Ref();
23 : }
24 :
25 : // assign
26 : scoped_ptr_refcount& operator=(scoped_ptr_refcount const& other) {
27 : if (this != &other) { // exclude self-assignment, which should be no-op
28 : if (NULL != ptr_) {
29 : ptr_->Unref();
30 : }
31 : ptr_ = other.ptr_->Ref();
32 : }
33 : return *this;
34 : }
35 :
36 14 : ~scoped_ptr_refcount() {
37 14 : if (NULL != ptr_) {
38 0 : ptr_->Unref();
39 0 : }
40 28 : }
41 :
42 10 : void reset(RC *p = NULL) {
43 10 : if (NULL != ptr_) {
44 5 : ptr_->Unref();
45 5 : }
46 10 : ptr_ = p;
47 10 : }
48 :
49 : // Accessors
50 : RC& operator*() const {
51 : return *ptr_; // may fault if ptr_ is NULL
52 : }
53 :
54 : RC* operator->() const {
55 10 : return ptr_;
56 : }
57 :
58 : RC* get() const { return ptr_; }
59 :
60 : /*
61 : * ptr eq, so same pointer, and not equality testing on contents.
62 : */
63 5 : bool operator==(RC const* p) const { return ptr_ == p; }
64 5 : bool operator!=(RC const* p) const { return ptr_ != p; }
65 :
66 : bool operator==(scoped_ptr_refcount const&p2) const {
67 : return ptr_ == p2.ptr;
68 : }
69 : bool operator!=(scoped_ptr_refcount const&p2) const {
70 : return ptr_ != p2.ptr;
71 : }
72 :
73 : void swap(scoped_ptr_refcount& p2) {
74 : RC* tmp = ptr_;
75 : ptr_ = p2.ptr_;
76 : p2.ptr_ = tmp;
77 : }
78 :
79 : RC* release() {
80 : RC* tmp = ptr_;
81 : ptr_ = NULL;
82 : return tmp;
83 : }
84 :
85 : private:
86 : RC* ptr_;
87 : };
88 :
89 : template<typename RC>
90 : void swap(scoped_ptr_refcount<RC>& a,
91 : scoped_ptr_refcount<RC>& b) {
92 : a.swap(b);
93 : }
94 :
95 : template<class RC> inline
96 : bool operator==(RC const* a,
97 : scoped_ptr_refcount<RC> const& b) {
98 : return a == b.get();
99 : }
100 :
101 : template<typename RC, typename DP> inline
102 : bool operator!=(RC const* a,
103 : scoped_ptr_refcount<RC> const& b) {
104 : return a != b.get();
105 : }
106 :
107 : } // namespace
108 :
109 : #endif /* NATIVE_CLIENT_SRC_SHARED_PLATFORM_SCOPED_PTR_REFCOUNT_H_ */
|