1 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_SCOPED_CFTYPEREF_H_ 6 #define BASE_SCOPED_CFTYPEREF_H_ 7 8 #include <CoreFoundation/CoreFoundation.h> 9 #include "base/basictypes.h" 10 11 // scoped_cftyperef<> is patterned after scoped_ptr<>, but maintains ownership 12 // of a CoreFoundation object: any object that can be represented as a 13 // CFTypeRef. Style deviations here are solely for compatibility with 14 // scoped_ptr<>'s interface, with which everyone is already familiar. 15 // 16 // When scoped_cftyperef<> takes ownership of an object (in the constructor or 17 // in reset()), it takes over the caller's existing ownership claim. The 18 // caller must own the object it gives to scoped_cftyperef<>, and relinquishes 19 // an ownership claim to that object. scoped_cftyperef<> does not call 20 // CFRetain(). 21 template<typename CFT> 22 class scoped_cftyperef { 23 public: 24 typedef CFT element_type; 25 26 explicit scoped_cftyperef(CFT object = NULL) object_(object)27 : object_(object) { 28 } 29 ~scoped_cftyperef()30 ~scoped_cftyperef() { 31 if (object_) 32 CFRelease(object_); 33 } 34 35 void reset(CFT object = NULL) { 36 if (object_) 37 CFRelease(object_); 38 object_ = object; 39 } 40 41 bool operator==(CFT that) const { 42 return object_ == that; 43 } 44 45 bool operator!=(CFT that) const { 46 return object_ != that; 47 } 48 CFT()49 operator CFT() const { 50 return object_; 51 } 52 get()53 CFT get() const { 54 return object_; 55 } 56 swap(scoped_cftyperef & that)57 void swap(scoped_cftyperef& that) { 58 CFT temp = that.object_; 59 that.object_ = object_; 60 object_ = temp; 61 } 62 63 // scoped_cftyperef<>::release() is like scoped_ptr<>::release. It is NOT 64 // a wrapper for CFRelease(). To force a scoped_cftyperef<> object to call 65 // CFRelease(), use scoped_cftyperef<>::reset(). release()66 CFT release() { 67 CFT temp = object_; 68 object_ = NULL; 69 return temp; 70 } 71 72 private: 73 CFT object_; 74 75 DISALLOW_COPY_AND_ASSIGN(scoped_cftyperef); 76 }; 77 78 #endif // BASE_SCOPED_CFTYPEREF_H_ 79