• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 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_GENERIC_H_
6 #define BASE_SCOPED_GENERIC_H_
7 
8 #include <stdlib.h>
9 
10 #include <algorithm>
11 
12 #include "base/compiler_specific.h"
13 
14 namespace base {
15 
16 // This class acts like unique_ptr with a custom deleter (although is slightly
17 // less fancy in some of the more escoteric respects) except that it keeps a
18 // copy of the object rather than a pointer, and we require that the contained
19 // object has some kind of "invalid" value.
20 //
21 // Defining a scoper based on this class allows you to get a scoper for
22 // non-pointer types without having to write custom code for set, reset, and
23 // move, etc. and get almost identical semantics that people are used to from
24 // unique_ptr.
25 //
26 // It is intended that you will typedef this class with an appropriate deleter
27 // to implement clean up tasks for objects that act like pointers from a
28 // resource management standpoint but aren't, such as file descriptors and
29 // various types of operating system handles. Using unique_ptr for these
30 // things requires that you keep a pointer to the handle valid for the lifetime
31 // of the scoper (which is easy to mess up).
32 //
33 // For an object to be able to be put into a ScopedGeneric, it must support
34 // standard copyable semantics and have a specific "invalid" value. The traits
35 // must define a free function and also the invalid value to assign for
36 // default-constructed and released objects.
37 //
38 //   struct FooScopedTraits {
39 //     // It's assumed that this is a fast inline function with little-to-no
40 //     // penalty for duplicate calls. This must be a static function even
41 //     // for stateful traits.
42 //     static int InvalidValue() {
43 //       return 0;
44 //     }
45 //
46 //     // This free function will not be called if f == InvalidValue()!
47 //     static void Free(int f) {
48 //       ::FreeFoo(f);
49 //     }
50 //   };
51 //
52 //   typedef ScopedGeneric<int, FooScopedTraits> ScopedFoo;
53 template <typename T, typename Traits>
54 class ScopedGeneric {
55  private:
56   // This must be first since it's used inline below.
57   //
58   // Use the empty base class optimization to allow us to have a D
59   // member, while avoiding any space overhead for it when D is an
60   // empty class.  See e.g. http://www.cantrip.org/emptyopt.html for a good
61   // discussion of this technique.
62   struct Data : public Traits {
DataData63     explicit Data(const T& in) : generic(in) {}
DataData64     Data(const T& in, const Traits& other) : Traits(other), generic(in) {}
65     T generic;
66   };
67 
68  public:
69   typedef T element_type;
70   typedef Traits traits_type;
71 
ScopedGeneric()72   ScopedGeneric() : data_(traits_type::InvalidValue()) {}
73 
74   // Constructor. Takes responsibility for freeing the resource associated with
75   // the object T.
ScopedGeneric(const element_type & value)76   explicit ScopedGeneric(const element_type& value) : data_(value) {}
77 
78   // Constructor. Allows initialization of a stateful traits object.
ScopedGeneric(const element_type & value,const traits_type & traits)79   ScopedGeneric(const element_type& value, const traits_type& traits)
80       : data_(value, traits) {}
81 
82   // Move constructor. Allows initialization from a ScopedGeneric rvalue.
ScopedGeneric(ScopedGeneric<T,Traits> && rvalue)83   ScopedGeneric(ScopedGeneric<T, Traits>&& rvalue)
84       : data_(rvalue.release(), rvalue.get_traits()) {}
85 
~ScopedGeneric()86   ~ScopedGeneric() { FreeIfNecessary(); }
87 
88   // operator=. Allows assignment from a ScopedGeneric rvalue.
89   ScopedGeneric& operator=(ScopedGeneric<T, Traits>&& rvalue) {
90     reset(rvalue.release());
91     return *this;
92   }
93 
94   // Frees the currently owned object, if any. Then takes ownership of a new
95   // object, if given. Self-resets are not allowed as on unique_ptr. See
96   // http://crbug.com/162971
97   void reset(const element_type& value = traits_type::InvalidValue()) {
98     if (data_.generic != traits_type::InvalidValue() && data_.generic == value)
99       abort();
100     FreeIfNecessary();
101     data_.generic = value;
102   }
103 
swap(ScopedGeneric & other)104   void swap(ScopedGeneric& other) {
105     // Standard swap idiom: 'using std::swap' ensures that std::swap is
106     // present in the overload set, but we call swap unqualified so that
107     // any more-specific overloads can be used, if available.
108     using std::swap;
109     swap(static_cast<Traits&>(data_), static_cast<Traits&>(other.data_));
110     swap(data_.generic, other.data_.generic);
111   }
112 
113   // Release the object. The return value is the current object held by this
114   // object. After this operation, this object will hold a null value, and
115   // will not own the object any more.
release()116   [[nodiscard]] element_type release() {
117     element_type old_generic = data_.generic;
118     data_.generic = traits_type::InvalidValue();
119     return old_generic;
120   }
121 
122   // Returns a raw pointer to the object storage, to allow the scoper to be used
123   // to receive and manage out-parameter values. Implies reset().
receive()124   [[nodiscard]] element_type* receive() {
125     reset();
126     return &data_.generic;
127   }
128 
get()129   const element_type& get() const { return data_.generic; }
130 
131   // Returns true if this object doesn't hold the special null value for the
132   // associated data type.
is_valid()133   bool is_valid() const { return data_.generic != traits_type::InvalidValue(); }
134 
135   bool operator==(const element_type& value) const {
136     return data_.generic == value;
137   }
138   bool operator!=(const element_type& value) const {
139     return data_.generic != value;
140   }
141 
get_traits()142   Traits& get_traits() { return data_; }
get_traits()143   const Traits& get_traits() const { return data_; }
144 
145  private:
FreeIfNecessary()146   void FreeIfNecessary() {
147     if (data_.generic != traits_type::InvalidValue()) {
148       data_.Free(data_.generic);
149       data_.generic = traits_type::InvalidValue();
150     }
151   }
152 
153   // Forbid comparison. If U != T, it totally doesn't make sense, and if U ==
154   // T, it still doesn't make sense because you should never have the same
155   // object owned by two different ScopedGenerics.
156   template <typename T2, typename Traits2>
157   bool operator==(const ScopedGeneric<T2, Traits2>& p2) const;
158   template <typename T2, typename Traits2>
159   bool operator!=(const ScopedGeneric<T2, Traits2>& p2) const;
160 
161   Data data_;
162 
163   ScopedGeneric(const ScopedGeneric&) = delete;
164   ScopedGeneric& operator=(const ScopedGeneric&) = delete;
165 };
166 
167 template <class T, class Traits>
swap(const ScopedGeneric<T,Traits> & a,const ScopedGeneric<T,Traits> & b)168 void swap(const ScopedGeneric<T, Traits>& a,
169           const ScopedGeneric<T, Traits>& b) {
170   a.swap(b);
171 }
172 
173 template <class T, class Traits>
174 bool operator==(const T& value, const ScopedGeneric<T, Traits>& scoped) {
175   return value == scoped.get();
176 }
177 
178 template <class T, class Traits>
179 bool operator!=(const T& value, const ScopedGeneric<T, Traits>& scoped) {
180   return value != scoped.get();
181 }
182 
183 }  // namespace base
184 
185 #endif  // BASE_SCOPED_GENERIC_H_
186