Ice 3.7 C++11 API Reference
UniqueRef.h
Go to the documentation of this file.
1 //
2 // Copyright (c) ZeroC, Inc. All rights reserved.
3 //
4 
5 #ifndef ICE_UNIQUE_REF_H
6 #define ICE_UNIQUE_REF_H
7 
8 #ifdef __APPLE__
9 
10 #include <CoreFoundation/CoreFoundation.h>
11 
12 namespace IceInternal
13 {
14 
15 //
16 // UniqueRef helper class for CoreFoundation classes, comparable to std::unique_ptr
17 //
18 template<typename R>
19 class UniqueRef
20 {
21 public:
22 
23  explicit UniqueRef(R ref = 0) :
24  _ref(ref)
25  {
26  }
27 
28  ~UniqueRef()
29  {
30  if(_ref != 0)
31  {
32  CFRelease(_ref);
33  }
34  }
35 
36  R release()
37  {
38  R r = _ref;
39  _ref = 0;
40  return r;
41  }
42 
43  void reset(R ref = 0)
44  {
45  //
46  // Support "self-reset" for CF objects. This is useful if CF allocation methods return
47  // the same object with an increased reference count.
48  //
49  //assert(ref == 0 || ref != _ref);
50 
51  if(_ref != 0)
52  {
53  CFRelease(_ref);
54  }
55  _ref = ref;
56  }
57 
58  void retain(R ref)
59  {
60  reset(ref ? (R)CFRetain(ref) : ref);
61  }
62 
63  R& get()
64  {
65  return _ref;
66  }
67 
68  R get() const
69  {
70  return _ref;
71  }
72 
73  operator bool() const
74  {
75  return _ref != 0;
76  }
77 
78  void swap(UniqueRef& a)
79  {
80  R tmp = a._ref;
81  a._ref = _ref;
82  _ref = tmp;
83  }
84 
85 private:
86 
87  UniqueRef(UniqueRef&);
88  UniqueRef& operator=(UniqueRef&);
89 
90  R _ref;
91 };
92 
93 }
94 
95 #endif
96 
97 #endif