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.
5 #ifndef BASE_SCOPED_GENERIC_H_
6 #define BASE_SCOPED_GENERIC_H_
12 #include "base/compiler_specific.h"
13 #include "base/logging.h"
14 #include "base/macros.h"
18 // This class acts like unique_ptr with a custom deleter (although is slightly
19 // less fancy in some of the more escoteric respects) except that it keeps a
20 // copy of the object rather than a pointer, and we require that the contained
21 // object has some kind of "invalid" value.
23 // Defining a scoper based on this class allows you to get a scoper for
24 // non-pointer types without having to write custom code for set, reset, and
25 // move, etc. and get almost identical semantics that people are used to from
28 // It is intended that you will typedef this class with an appropriate deleter
29 // to implement clean up tasks for objects that act like pointers from a
30 // resource management standpoint but aren't, such as file descriptors and
31 // various types of operating system handles. Using unique_ptr for these
32 // things requires that you keep a pointer to the handle valid for the lifetime
33 // of the scoper (which is easy to mess up).
35 // For an object to be able to be put into a ScopedGeneric, it must support
36 // standard copyable semantics and have a specific "invalid" value. The traits
37 // must define a free function and also the invalid value to assign for
38 // default-constructed and released objects.
40 // struct FooScopedTraits {
41 // // It's assumed that this is a fast inline function with little-to-no
42 // // penalty for duplicate calls. This must be a static function even
43 // // for stateful traits.
44 // static int InvalidValue() {
48 // // This free function will not be called if f == InvalidValue()!
49 // static void Free(int f) {
54 // typedef ScopedGeneric<int, FooScopedTraits> ScopedFoo;
56 // A Traits type may choose to track ownership of objects in parallel with
57 // ScopedGeneric. To do so, it must implement the Acquire and Release methods,
58 // which will be called by ScopedGeneric during ownership transfers and extend
59 // the ScopedGenericOwnershipTracking tag type.
61 // struct BarScopedTraits : public ScopedGenericOwnershipTracking {
62 // using ScopedGenericType = ScopedGeneric<int, BarScopedTraits>;
63 // static int InvalidValue() {
67 // static void Free(int b) {
71 // static void Acquire(const ScopedGenericType& owner, int b) {
72 // ::TrackAcquisition(b, owner);
75 // static void Release(const ScopedGenericType& owner, int b) {
76 // ::TrackRelease(b, owner);
80 // typedef ScopedGeneric<int, BarScopedTraits> ScopedBar;
81 struct ScopedGenericOwnershipTracking {};
83 template<typename T, typename Traits>
86 // This must be first since it's used inline below.
88 // Use the empty base class optimization to allow us to have a D
89 // member, while avoiding any space overhead for it when D is an
90 // empty class. See e.g. http://www.cantrip.org/emptyopt.html for a good
91 // discussion of this technique.
92 struct Data : public Traits {
93 explicit Data(const T& in) : generic(in) {}
94 Data(const T& in, const Traits& other) : Traits(other), generic(in) {}
99 typedef T element_type;
100 typedef Traits traits_type;
102 ScopedGeneric() : data_(traits_type::InvalidValue()) {}
104 // Constructor. Takes responsibility for freeing the resource associated with
106 explicit ScopedGeneric(const element_type& value) : data_(value) {
107 TrackAcquire(data_.generic);
110 // Constructor. Allows initialization of a stateful traits object.
111 ScopedGeneric(const element_type& value, const traits_type& traits)
112 : data_(value, traits) {
113 TrackAcquire(data_.generic);
116 // Move constructor. Allows initialization from a ScopedGeneric rvalue.
117 ScopedGeneric(ScopedGeneric<T, Traits>&& rvalue)
118 : data_(rvalue.release(), rvalue.get_traits()) {
119 TrackAcquire(data_.generic);
123 CHECK(!receiving_) << "ScopedGeneric destroyed with active receiver";
127 // operator=. Allows assignment from a ScopedGeneric rvalue.
128 ScopedGeneric& operator=(ScopedGeneric<T, Traits>&& rvalue) {
129 reset(rvalue.release());
133 // Frees the currently owned object, if any. Then takes ownership of a new
134 // object, if given. Self-resets are not allowd as on unique_ptr. See
135 // http://crbug.com/162971
136 void reset(const element_type& value = traits_type::InvalidValue()) {
137 if (data_.generic != traits_type::InvalidValue() && data_.generic == value)
140 data_.generic = value;
144 void swap(ScopedGeneric& other) {
145 if (&other == this) {
149 TrackRelease(data_.generic);
150 other.TrackRelease(other.data_.generic);
152 // Standard swap idiom: 'using std::swap' ensures that std::swap is
153 // present in the overload set, but we call swap unqualified so that
154 // any more-specific overloads can be used, if available.
156 swap(static_cast<Traits&>(data_), static_cast<Traits&>(other.data_));
157 swap(data_.generic, other.data_.generic);
159 TrackAcquire(data_.generic);
160 other.TrackAcquire(other.data_.generic);
163 // Release the object. The return value is the current object held by this
164 // object. After this operation, this object will hold a null value, and
165 // will not own the object any more.
166 element_type release() WARN_UNUSED_RESULT {
167 element_type old_generic = data_.generic;
168 data_.generic = traits_type::InvalidValue();
169 TrackRelease(old_generic);
173 // A helper class that provides a T* that can be used to take ownership of
174 // a value returned from a function via out-parameter. When the Receiver is
175 // destructed (which should usually be at the end of the statement in which
176 // receive is called), ScopedGeneric::reset() will be called with the
179 // In the simple case of a function that assigns the value before it returns,
180 // C++'s lifetime extension can be used as follows:
183 // bool result = GetFoo(ScopedFoo::Receiver(foo).get());
185 // Note that the lifetime of the Receiver is extended until the semicolon,
186 // and ScopedGeneric is assigned the value upon destruction of the Receiver,
187 // so the following code would not work:
191 // UseFoo(&foo, GetFoo(ScopedFoo::Receiver(foo).get()));
193 // In more complicated scenarios, you may need to provide an explicit scope
194 // for the Receiver, as in the following:
196 // std::vector<ScopedFoo> foos(64);
199 // std::vector<ScopedFoo::Receiver> foo_receivers;
200 // for (auto foo : foos) {
201 // foo_receivers_.emplace_back(foo);
203 // for (auto receiver : foo_receivers) {
204 // SubmitGetFooRequest(receiver.get());
206 // WaitForFooRequests();
211 explicit Receiver(ScopedGeneric& parent) : scoped_generic_(&parent) {
212 CHECK(!scoped_generic_->receiving_)
213 << "attempted to construct Receiver for ScopedGeneric with existing "
215 scoped_generic_->receiving_ = true;
219 if (scoped_generic_) {
220 CHECK(scoped_generic_->receiving_);
221 scoped_generic_->reset(value_);
222 scoped_generic_->receiving_ = false;
226 Receiver(Receiver&& move) {
227 CHECK(!used_) << "moving into already-used Receiver";
228 CHECK(!move.used_) << "moving from already-used Receiver";
229 scoped_generic_ = move.scoped_generic_;
230 move.scoped_generic_ = nullptr;
233 Receiver& operator=(Receiver&& move) {
234 CHECK(!used_) << "moving into already-used Receiver";
235 CHECK(!move.used_) << "moving from already-used Receiver";
236 scoped_generic_ = move.scoped_generic_;
237 move.scoped_generic_ = nullptr;
240 // We hand out a pointer to a field in Receiver instead of directly to
241 // ScopedGeneric's internal storage in order to make it so that users can't
242 // accidentally silently break ScopedGeneric's invariants. This way, an
243 // incorrect use-after-scope-exit is more detectable by ASan or static
244 // analysis tools, as the pointer is only valid for the lifetime of the
245 // Receiver, not the ScopedGeneric.
252 T value_ = Traits::InvalidValue();
253 ScopedGeneric* scoped_generic_;
256 DISALLOW_COPY_AND_ASSIGN(Receiver);
259 const element_type& get() const { return data_.generic; }
261 // Returns true if this object doesn't hold the special null value for the
262 // associated data type.
263 bool is_valid() const { return data_.generic != traits_type::InvalidValue(); }
265 bool operator==(const element_type& value) const {
266 return data_.generic == value;
268 bool operator!=(const element_type& value) const {
269 return data_.generic != value;
272 Traits& get_traits() { return data_; }
273 const Traits& get_traits() const { return data_; }
276 void FreeIfNecessary() {
277 if (data_.generic != traits_type::InvalidValue()) {
278 TrackRelease(data_.generic);
279 data_.Free(data_.generic);
280 data_.generic = traits_type::InvalidValue();
284 template <typename Void = void>
285 typename std::enable_if_t<
286 std::is_base_of<ScopedGenericOwnershipTracking, Traits>::value,
288 TrackAcquire(const T& value) {
289 if (value != traits_type::InvalidValue()) {
290 data_.Acquire(static_cast<const ScopedGeneric&>(*this), value);
294 template <typename Void = void>
295 typename std::enable_if_t<
296 !std::is_base_of<ScopedGenericOwnershipTracking, Traits>::value,
298 TrackAcquire(const T& value) {}
300 template <typename Void = void>
301 typename std::enable_if_t<
302 std::is_base_of<ScopedGenericOwnershipTracking, Traits>::value,
304 TrackRelease(const T& value) {
305 if (value != traits_type::InvalidValue()) {
306 data_.Release(static_cast<const ScopedGeneric&>(*this), value);
310 template <typename Void = void>
311 typename std::enable_if_t<
312 !std::is_base_of<ScopedGenericOwnershipTracking, Traits>::value,
314 TrackRelease(const T& value) {}
316 // Forbid comparison. If U != T, it totally doesn't make sense, and if U ==
317 // T, it still doesn't make sense because you should never have the same
318 // object owned by two different ScopedGenerics.
319 template <typename T2, typename Traits2> bool operator==(
320 const ScopedGeneric<T2, Traits2>& p2) const;
321 template <typename T2, typename Traits2> bool operator!=(
322 const ScopedGeneric<T2, Traits2>& p2) const;
325 bool receiving_ = false;
327 DISALLOW_COPY_AND_ASSIGN(ScopedGeneric);
330 template<class T, class Traits>
331 void swap(const ScopedGeneric<T, Traits>& a,
332 const ScopedGeneric<T, Traits>& b) {
336 template<class T, class Traits>
337 bool operator==(const T& value, const ScopedGeneric<T, Traits>& scoped) {
338 return value == scoped.get();
341 template<class T, class Traits>
342 bool operator!=(const T& value, const ScopedGeneric<T, Traits>& scoped) {
343 return value != scoped.get();
348 #endif // BASE_SCOPED_GENERIC_H_