1 // Copyright (c) 2012 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.
5 #ifndef BASE_MAC_SCOPED_CFTYPEREF_H_
6 #define BASE_MAC_SCOPED_CFTYPEREF_H_
8 #include <CoreFoundation/CoreFoundation.h>
10 #include "base/basictypes.h"
11 #include "base/compiler_specific.h"
12 #include "base/memory/scoped_policy.h"
16 // ScopedCFTypeRef<> is patterned after scoped_ptr<>, but maintains ownership
17 // of a CoreFoundation object: any object that can be represented as a
18 // CFTypeRef. Style deviations here are solely for compatibility with
19 // scoped_ptr<>'s interface, with which everyone is already familiar.
21 // By default, ScopedCFTypeRef<> takes ownership of an object (in the
22 // constructor or in reset()) by taking over the caller's existing ownership
23 // claim. The caller must own the object it gives to ScopedCFTypeRef<>, and
24 // relinquishes an ownership claim to that object. ScopedCFTypeRef<> does not
25 // call CFRetain(). This behavior is parameterized by the |OwnershipPolicy|
26 // enum. If the value |RETAIN| is passed (in the constructor or in reset()),
27 // then ScopedCFTypeRef<> will call CFRetain() on the object, and the initial
28 // ownership is not changed.
30 template<typename CFT
>
31 class ScopedCFTypeRef
{
33 typedef CFT element_type
;
35 explicit ScopedCFTypeRef(
37 base::scoped_policy::OwnershipPolicy policy
= base::scoped_policy::ASSUME
)
39 if (object_
&& policy
== base::scoped_policy::RETAIN
)
43 ScopedCFTypeRef(const ScopedCFTypeRef
<CFT
>& that
)
44 : object_(that
.object_
) {
54 ScopedCFTypeRef
& operator=(const ScopedCFTypeRef
<CFT
>& that
) {
55 reset(that
.get(), base::scoped_policy::RETAIN
);
59 void reset(CFT object
= NULL
,
60 base::scoped_policy::OwnershipPolicy policy
=
61 base::scoped_policy::ASSUME
) {
62 if (object
&& policy
== base::scoped_policy::RETAIN
)
69 bool operator==(CFT that
) const {
70 return object_
== that
;
73 bool operator!=(CFT that
) const {
74 return object_
!= that
;
77 operator CFT() const {
85 void swap(ScopedCFTypeRef
& that
) {
86 CFT temp
= that
.object_
;
87 that
.object_
= object_
;
91 // ScopedCFTypeRef<>::release() is like scoped_ptr<>::release. It is NOT
92 // a wrapper for CFRelease(). To force a ScopedCFTypeRef<> object to call
93 // CFRelease(), use ScopedCFTypeRef<>::reset().
94 CFT
release() WARN_UNUSED_RESULT
{
106 #endif // BASE_MAC_SCOPED_CFTYPEREF_H_