blob: 7b4f1e68350be1daf42210d49d2791b9c6576de2 [file] [log] [blame]
license.botf003cfe2008-08-24 09:55:55 +09001// 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.
initial.commit3f4a7322008-07-27 06:49:38 +09004
avi@google.com0edcae82008-08-23 04:55:26 +09005#ifndef BASE_SCOPED_CFTYPEREF_H_
6#define BASE_SCOPED_CFTYPEREF_H_
initial.commit3f4a7322008-07-27 06:49:38 +09007
8#include <CoreFoundation/CoreFoundation.h>
avi@google.com0edcae82008-08-23 04:55:26 +09009#include "base/basictypes.h"
initial.commit3f4a7322008-07-27 06:49:38 +090010
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.
mark@chromium.orgde9c22c2009-03-24 00:15:29 +090015//
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
mark@chromium.orgdaef2832009-03-24 04:21:18 +090018// 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().
initial.commit3f4a7322008-07-27 06:49:38 +090021template<typename CFT>
22class scoped_cftyperef {
23 public:
24 typedef CFT element_type;
25
26 explicit scoped_cftyperef(CFT object = NULL)
27 : object_(object) {
28 }
29
30 ~scoped_cftyperef() {
31 if (object_)
32 CFRelease(object_);
33 }
34
35 void reset(CFT object = NULL) {
mark@chromium.orgdaef2832009-03-24 04:21:18 +090036 if (object_)
37 CFRelease(object_);
38 object_ = object;
initial.commit3f4a7322008-07-27 06:49:38 +090039 }
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
49 operator CFT() const {
50 return object_;
51 }
52
53 CFT get() const {
54 return object_;
55 }
56
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().
66 CFT release() {
67 CFT temp = object_;
68 object_ = NULL;
69 return temp;
70 }
71
72 private:
73 CFT object_;
74
avi@google.com0edcae82008-08-23 04:55:26 +090075 DISALLOW_COPY_AND_ASSIGN(scoped_cftyperef);
initial.commit3f4a7322008-07-27 06:49:38 +090076};
77
avi@google.com0edcae82008-08-23 04:55:26 +090078#endif // BASE_SCOPED_CFTYPEREF_H_