2 * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
11 #ifndef SYSTEM_WRAPPERS_INTERFACE_SCOPED_REFPTR_H_
12 #define SYSTEM_WRAPPERS_INTERFACE_SCOPED_REFPTR_H_
18 // Extracted from Chromium's src/base/memory/ref_counted.h.
21 // A smart pointer class for reference counted objects. Use this class instead
22 // of calling AddRef and Release manually on a reference counted object to
23 // avoid common memory leaks caused by forgetting to Release an object
24 // reference. Sample usage:
26 // class MyFoo : public RefCounted<MyFoo> {
30 // void some_function() {
31 // scoped_refptr<MyFoo> foo = new MyFoo();
32 // foo->Method(param);
33 // // |foo| is released when this function returns
36 // void some_other_function() {
37 // scoped_refptr<MyFoo> foo = new MyFoo();
39 // foo = NULL; // explicitly releases |foo|
42 // foo->Method(param);
45 // The above examples show how scoped_refptr<T> acts like a pointer to T.
46 // Given two scoped_refptr<T> classes, it is also possible to exchange
47 // references between the two objects, like so:
50 // scoped_refptr<MyFoo> a = new MyFoo();
51 // scoped_refptr<MyFoo> b;
54 // // now, |b| references the MyFoo object, and |a| references NULL.
57 // To make both |a| and |b| in the above example reference the same MyFoo
58 // object, simply use the assignment operator:
61 // scoped_refptr<MyFoo> a = new MyFoo();
62 // scoped_refptr<MyFoo> b;
65 // // now, |a| and |b| each own a reference to the same MyFoo object.
71 scoped_refptr() : ptr_(NULL) {
74 scoped_refptr(T* p) : ptr_(p) {
79 scoped_refptr(const scoped_refptr<T>& r) : ptr_(r.ptr_) {
85 scoped_refptr(const scoped_refptr<U>& r) : ptr_(r.get()) {
95 T* get() const { return ptr_; }
96 operator T*() const { return ptr_; }
97 T* operator->() const { return ptr_; }
100 // The return value is the current pointer held by this object.
101 // If this object holds a NULL pointer, the return value is NULL.
102 // After this operation, this object will hold a NULL pointer,
103 // and will not own the object any more.
110 scoped_refptr<T>& operator=(T* p) {
111 // AddRef first so that self assignment should work
120 scoped_refptr<T>& operator=(const scoped_refptr<T>& r) {
121 return *this = r.ptr_;
124 template <typename U>
125 scoped_refptr<T>& operator=(const scoped_refptr<U>& r) {
126 return *this = r.get();
135 void swap(scoped_refptr<T>& r) {
142 } // namespace webrtc
144 #endif // SYSTEM_WRAPPERS_INTERFACE_SCOPED_REFPTR_H_