• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2010 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_MAC_SCOPED_CFTYPEREF_H_
6 #define BASE_MAC_SCOPED_CFTYPEREF_H_
7 #pragma once
8 
9 #include <CoreFoundation/CoreFoundation.h>
10 
11 #include "base/basictypes.h"
12 #include "base/compiler_specific.h"
13 
14 namespace base {
15 namespace mac {
16 
17 // ScopedCFTypeRef<> is patterned after scoped_ptr<>, but maintains ownership
18 // of a CoreFoundation object: any object that can be represented as a
19 // CFTypeRef.  Style deviations here are solely for compatibility with
20 // scoped_ptr<>'s interface, with which everyone is already familiar.
21 //
22 // When ScopedCFTypeRef<> takes ownership of an object (in the constructor or
23 // in reset()), it takes over the caller's existing ownership claim.  The
24 // caller must own the object it gives to ScopedCFTypeRef<>, and relinquishes
25 // an ownership claim to that object.  ScopedCFTypeRef<> does not call
26 // CFRetain().
27 template<typename CFT>
28 class ScopedCFTypeRef {
29  public:
30   typedef CFT element_type;
31 
32   explicit ScopedCFTypeRef(CFT object = NULL)
object_(object)33       : object_(object) {
34   }
35 
~ScopedCFTypeRef()36   ~ScopedCFTypeRef() {
37     if (object_)
38       CFRelease(object_);
39   }
40 
41   void reset(CFT object = NULL) {
42     if (object_)
43       CFRelease(object_);
44     object_ = object;
45   }
46 
47   bool operator==(CFT that) const {
48     return object_ == that;
49   }
50 
51   bool operator!=(CFT that) const {
52     return object_ != that;
53   }
54 
CFT()55   operator CFT() const {
56     return object_;
57   }
58 
get()59   CFT get() const {
60     return object_;
61   }
62 
swap(ScopedCFTypeRef & that)63   void swap(ScopedCFTypeRef& that) {
64     CFT temp = that.object_;
65     that.object_ = object_;
66     object_ = temp;
67   }
68 
69   // ScopedCFTypeRef<>::release() is like scoped_ptr<>::release.  It is NOT
70   // a wrapper for CFRelease().  To force a ScopedCFTypeRef<> object to call
71   // CFRelease(), use ScopedCFTypeRef<>::reset().
release()72   CFT release() WARN_UNUSED_RESULT {
73     CFT temp = object_;
74     object_ = NULL;
75     return temp;
76   }
77 
78  private:
79   CFT object_;
80 
81   DISALLOW_COPY_AND_ASSIGN(ScopedCFTypeRef);
82 };
83 
84 }  // namespace mac
85 }  // namespace base
86 
87 #endif  // BASE_MAC_SCOPED_CFTYPEREF_H_
88