• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 //
5 // The original source code is from:
6 // https://code.google.com/p/libphonenumber/source/browse/trunk/cpp/src/phonenumbers/base/memory/scoped_ptr.h?r=621
7 
8 #ifndef I18N_ADDRESSINPUT_UTIL_SCOPED_PTR_H_
9 #define I18N_ADDRESSINPUT_UTIL_SCOPED_PTR_H_
10 
11 // This is an implementation designed to match the anticipated future TR2
12 // implementation of the scoped_ptr class and scoped_ptr_malloc (deprecated).
13 
14 #include <libaddressinput/util/basictypes.h>
15 #include <libaddressinput/util/template_util.h>
16 
17 #include <algorithm>  // For std::swap().
18 #include <cassert>
19 #include <cstddef>
20 #include <cstdlib>
21 
22 namespace i18n {
23 namespace addressinput {
24 
25 // Function object which deletes its parameter, which must be a pointer.
26 // If C is an array type, invokes 'delete[]' on the parameter; otherwise,
27 // invokes 'delete'. The default deleter for scoped_ptr<T>.
28 template <class T>
29 struct DefaultDeleter {
DefaultDeleterDefaultDeleter30   DefaultDeleter() {}
DefaultDeleterDefaultDeleter31   template <typename U> DefaultDeleter(const DefaultDeleter<U>& other) {
32     // IMPLEMENTATION NOTE: C++11 20.7.1.1.2p2 only provides this constructor
33     // if U* is implicitly convertible to T* and U is not an array type.
34     //
35     // Correct implementation should use SFINAE to disable this
36     // constructor. However, since there are no other 1-argument constructors,
37     // using a COMPILE_ASSERT() based on is_convertible<> and requiring
38     // complete types is simpler and will cause compile failures for equivalent
39     // misuses.
40     //
41     // Note, the is_convertible<U*, T*> check also ensures that U is not an
42     // array. T is guaranteed to be a non-array, so any U* where U is an array
43     // cannot convert to T*.
44     enum { T_must_be_complete = sizeof(T) };
45     enum { U_must_be_complete = sizeof(U) };
46     COMPILE_ASSERT((is_convertible<U*, T*>::value),
47                    U_ptr_must_implicitly_convert_to_T_ptr);
48   }
operatorDefaultDeleter49   inline void operator()(T* ptr) const {
50     enum { type_must_be_complete = sizeof(T) };
51     delete ptr;
52   }
53 };
54 
55 // Specialization of DefaultDeleter for array types.
56 template <class T>
57 struct DefaultDeleter<T[]> {
58   inline void operator()(T* ptr) const {
59     enum { type_must_be_complete = sizeof(T) };
60     delete[] ptr;
61   }
62 
63  private:
64   // Disable this operator for any U != T because it is undefined to execute
65   // an array delete when the static type of the array mismatches the dynamic
66   // type.
67   //
68   // References:
69   //   C++98 [expr.delete]p3
70   //   http://cplusplus.github.com/LWG/lwg-defects.html#938
71   template <typename U> void operator()(U* array) const;
72 };
73 
74 template <class T, int n>
75 struct DefaultDeleter<T[n]> {
76   // Never allow someone to declare something like scoped_ptr<int[10]>.
77   COMPILE_ASSERT(sizeof(T) == -1, do_not_use_array_with_size_as_type);
78 };
79 
80 // Function object which invokes 'free' on its parameter, which must be
81 // a pointer. Can be used to store malloc-allocated pointers in scoped_ptr:
82 //
83 // scoped_ptr<int, base::FreeDeleter> foo_ptr(
84 //     static_cast<int*>(malloc(sizeof(int))));
85 struct FreeDeleter {
86   inline void operator()(void* ptr) const {
87     free(ptr);
88   }
89 };
90 
91 // Minimal implementation of the core logic of scoped_ptr, suitable for
92 // reuse in both scoped_ptr and its specializations.
93 template <class T, class D>
94 class scoped_ptr_impl {
95  public:
96   explicit scoped_ptr_impl(T* p) : data_(p) { }
97 
98   // Initializer for deleters that have data parameters.
99   scoped_ptr_impl(T* p, const D& d) : data_(p, d) {}
100 
101   // Templated constructor that destructively takes the value from another
102   // scoped_ptr_impl.
103   template <typename U, typename V>
104   scoped_ptr_impl(scoped_ptr_impl<U, V>* other)
105       : data_(other->release(), other->get_deleter()) {
106     // We do not support move-only deleters.  We could modify our move
107     // emulation to have base::subtle::move() and base::subtle::forward()
108     // functions that are imperfect emulations of their C++11 equivalents,
109     // but until there's a requirement, just assume deleters are copyable.
110   }
111 
112   template <typename U, typename V>
113   void TakeState(scoped_ptr_impl<U, V>* other) {
114     // See comment in templated constructor above regarding lack of support
115     // for move-only deleters.
116     reset(other->release());
117     get_deleter() = other->get_deleter();
118   }
119 
120   ~scoped_ptr_impl() {
121     if (data_.ptr != NULL) {
122       // Not using get_deleter() saves one function call in non-optimized
123       // builds.
124       static_cast<D&>(data_)(data_.ptr);
125     }
126   }
127 
128   void reset(T* p) {
129     // This is a self-reset, which is no longer allowed: http://crbug.com/162971
130     if (p != NULL && p == data_.ptr)
131       abort();
132 
133     // Note that running data_.ptr = p can lead to undefined behavior if
134     // get_deleter()(get()) deletes this. In order to pevent this, reset()
135     // should update the stored pointer before deleting its old value.
136     //
137     // However, changing reset() to use that behavior may cause current code to
138     // break in unexpected ways. If the destruction of the owned object
139     // dereferences the scoped_ptr when it is destroyed by a call to reset(),
140     // then it will incorrectly dispatch calls to |p| rather than the original
141     // value of |data_.ptr|.
142     //
143     // During the transition period, set the stored pointer to NULL while
144     // deleting the object. Eventually, this safety check will be removed to
145     // prevent the scenario initially described from occuring and
146     // http://crbug.com/176091 can be closed.
147     T* old = data_.ptr;
148     data_.ptr = NULL;
149     if (old != NULL)
150       static_cast<D&>(data_)(old);
151     data_.ptr = p;
152   }
153 
154   T* get() const { return data_.ptr; }
155 
156   D& get_deleter() { return data_; }
157   const D& get_deleter() const { return data_; }
158 
159   void swap(scoped_ptr_impl& p2) {
160     // Standard swap idiom: 'using std::swap' ensures that std::swap is
161     // present in the overload set, but we call swap unqualified so that
162     // any more-specific overloads can be used, if available.
163     using std::swap;
164     swap(static_cast<D&>(data_), static_cast<D&>(p2.data_));
165     swap(data_.ptr, p2.data_.ptr);
166   }
167 
168   T* release() {
169     T* old_ptr = data_.ptr;
170     data_.ptr = NULL;
171     return old_ptr;
172   }
173 
174  private:
175   // Needed to allow type-converting constructor.
176   template <typename U, typename V> friend class scoped_ptr_impl;
177 
178   // Use the empty base class optimization to allow us to have a D
179   // member, while avoiding any space overhead for it when D is an
180   // empty class.  See e.g. http://www.cantrip.org/emptyopt.html for a good
181   // discussion of this technique.
182   struct Data : public D {
183     explicit Data(T* ptr_in) : ptr(ptr_in) {}
184     Data(T* ptr_in, const D& other) : D(other), ptr(ptr_in) {}
185     T* ptr;
186   };
187 
188   Data data_;
189 
190   DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl);
191 };
192 
193 // A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
194 // automatically deletes the pointer it holds (if any).
195 // That is, scoped_ptr<T> owns the T object that it points to.
196 // Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object.
197 // Also like T*, scoped_ptr<T> is thread-compatible, and once you
198 // dereference it, you get the thread safety guarantees of T.
199 //
200 // The size of scoped_ptr is small. On most compilers, when using the
201 // DefaultDeleter, sizeof(scoped_ptr<T>) == sizeof(T*). Custom deleters will
202 // increase the size proportional to whatever state they need to have. See
203 // comments inside scoped_ptr_impl<> for details.
204 //
205 // Current implementation targets having a strict subset of  C++11's
206 // unique_ptr<> features. Known deficiencies include not supporting move-only
207 // deleteres, function pointers as deleters, and deleters with reference
208 // types.
209 template <class T, class D = DefaultDeleter<T> >
210 class scoped_ptr {
211  public:
212   // The element and deleter types.
213   typedef T element_type;
214   typedef D deleter_type;
215 
216   // Constructor.  Defaults to initializing with NULL.
217   scoped_ptr() : impl_(NULL) { }
218 
219   // Constructor.  Takes ownership of p.
220   explicit scoped_ptr(element_type* p) : impl_(p) { }
221 
222   // Constructor.  Allows initialization of a stateful deleter.
223   scoped_ptr(element_type* p, const D& d) : impl_(p, d) { }
224 
225   // Constructor.  Allows construction from a scoped_ptr rvalue for a
226   // convertible type and deleter.
227   //
228   // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this constructor distinct
229   // from the normal move constructor. By C++11 20.7.1.2.1.21, this constructor
230   // has different post-conditions if D is a reference type. Since this
231   // implementation does not support deleters with reference type,
232   // we do not need a separate move constructor allowing us to avoid one
233   // use of SFINAE. You only need to care about this if you modify the
234   // implementation of scoped_ptr.
235   template <typename U, typename V>
236   scoped_ptr(scoped_ptr<U, V> other) : impl_(&other.impl_) {
237     COMPILE_ASSERT(!is_array<U>::value, U_cannot_be_an_array);
238   }
239 
240   // operator=.  Allows assignment from a scoped_ptr rvalue for a convertible
241   // type and deleter.
242   //
243   // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this operator= distinct from
244   // the normal move assignment operator. By C++11 20.7.1.2.3.4, this templated
245   // form has different requirements on for move-only Deleters. Since this
246   // implementation does not support move-only Deleters, we do not need a
247   // separate move assignment operator allowing us to avoid one use of SFINAE.
248   // You only need to care about this if you modify the implementation of
249   // scoped_ptr.
250   template <typename U, typename V>
251   scoped_ptr& operator=(scoped_ptr<U, V> rhs) {
252     COMPILE_ASSERT(!is_array<U>::value, U_cannot_be_an_array);
253     impl_.TakeState(&rhs.impl_);
254     return *this;
255   }
256 
257   // Reset.  Deletes the currently owned object, if any.
258   // Then takes ownership of a new object, if given.
259   void reset(element_type* p = NULL) { impl_.reset(p); }
260 
261   // Accessors to get the owned object.
262   // operator* and operator-> will assert() if there is no current object.
263   element_type& operator*() const {
264     assert(impl_.get() != NULL);
265     return *impl_.get();
266   }
267   element_type* operator->() const  {
268     assert(impl_.get() != NULL);
269     return impl_.get();
270   }
271   element_type* get() const { return impl_.get(); }
272 
273   // Access to the deleter.
274   deleter_type& get_deleter() { return impl_.get_deleter(); }
275   const deleter_type& get_deleter() const { return impl_.get_deleter(); }
276 
277   // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
278   // implicitly convertible to a real bool (which is dangerous).
279  private:
280   typedef scoped_ptr_impl<element_type, deleter_type> scoped_ptr::*Testable;
281 
282  public:
283   operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; }
284 
285   // Comparison operators.
286   // These return whether two scoped_ptr refer to the same object, not just to
287   // two different but equal objects.
288   bool operator==(const element_type* p) const { return impl_.get() == p; }
289   bool operator!=(const element_type* p) const { return impl_.get() != p; }
290 
291   // Swap two scoped pointers.
292   void swap(scoped_ptr& p2) {
293     impl_.swap(p2.impl_);
294   }
295 
296   // Release a pointer.
297   // The return value is the current pointer held by this object.
298   // If this object holds a NULL pointer, the return value is NULL.
299   // After this operation, this object will hold a NULL pointer,
300   // and will not own the object any more.
301   element_type* release() {
302     return impl_.release();
303   }
304 
305  private:
306   // Needed to reach into |impl_| in the constructor.
307   template <typename U, typename V> friend class scoped_ptr;
308   scoped_ptr_impl<element_type, deleter_type> impl_;
309 
310   // Forbid comparison of scoped_ptr types.  If U != T, it totally
311   // doesn't make sense, and if U == T, it still doesn't make sense
312   // because you should never have the same object owned by two different
313   // scoped_ptrs.
314   template <class U> bool operator==(scoped_ptr<U> const& p2) const;
315   template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
316 };
317 
318 template <class T, class D>
319 class scoped_ptr<T[], D> {
320  public:
321   // The element and deleter types.
322   typedef T element_type;
323   typedef D deleter_type;
324 
325   // Constructor.  Defaults to initializing with NULL.
326   scoped_ptr() : impl_(NULL) { }
327 
328   // Constructor. Stores the given array. Note that the argument's type
329   // must exactly match T*. In particular:
330   // - it cannot be a pointer to a type derived from T, because it is
331   //   inherently unsafe in the general case to access an array through a
332   //   pointer whose dynamic type does not match its static type (eg., if
333   //   T and the derived types had different sizes access would be
334   //   incorrectly calculated). Deletion is also always undefined
335   //   (C++98 [expr.delete]p3). If you're doing this, fix your code.
336   // - it cannot be NULL, because NULL is an integral expression, not a
337   //   pointer to T. Use the no-argument version instead of explicitly
338   //   passing NULL.
339   // - it cannot be const-qualified differently from T per unique_ptr spec
340   //   (http://cplusplus.github.com/LWG/lwg-active.html#2118). Users wanting
341   //   to work around this may use implicit_cast<const T*>().
342   //   However, because of the first bullet in this comment, users MUST
343   //   NOT use implicit_cast<Base*>() to upcast the static type of the array.
344   explicit scoped_ptr(element_type* array) : impl_(array) { }
345 
346   // Reset.  Deletes the currently owned array, if any.
347   // Then takes ownership of a new object, if given.
348   void reset(element_type* array = NULL) { impl_.reset(array); }
349 
350   // Accessors to get the owned array.
351   element_type& operator[](size_t i) const {
352     assert(impl_.get() != NULL);
353     return impl_.get()[i];
354   }
355   element_type* get() const { return impl_.get(); }
356 
357   // Access to the deleter.
358   deleter_type& get_deleter() { return impl_.get_deleter(); }
359   const deleter_type& get_deleter() const { return impl_.get_deleter(); }
360 
361   // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
362   // implicitly convertible to a real bool (which is dangerous).
363  private:
364   typedef scoped_ptr_impl<element_type, deleter_type> scoped_ptr::*Testable;
365 
366  public:
367   operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; }
368 
369   // Comparison operators.
370   // These return whether two scoped_ptr refer to the same object, not just to
371   // two different but equal objects.
372   bool operator==(element_type* array) const { return impl_.get() == array; }
373   bool operator!=(element_type* array) const { return impl_.get() != array; }
374 
375   // Swap two scoped pointers.
376   void swap(scoped_ptr& p2) {
377     impl_.swap(p2.impl_);
378   }
379 
380   // Release a pointer.
381   // The return value is the current pointer held by this object.
382   // If this object holds a NULL pointer, the return value is NULL.
383   // After this operation, this object will hold a NULL pointer,
384   // and will not own the object any more.
385   element_type* release() {
386     return impl_.release();
387   }
388 
389  private:
390   // Force element_type to be a complete type.
391   enum { type_must_be_complete = sizeof(element_type) };
392 
393   // Actually hold the data.
394   scoped_ptr_impl<element_type, deleter_type> impl_;
395 
396   // Disable initialization from any type other than element_type*, by
397   // providing a constructor that matches such an initialization, but is
398   // private and has no definition. This is disabled because it is not safe to
399   // call delete[] on an array whose static type does not match its dynamic
400   // type.
401   template <typename U> explicit scoped_ptr(U* array);
402   explicit scoped_ptr(int disallow_construction_from_null);
403 
404   // Disable reset() from any type other than element_type*, for the same
405   // reasons as the constructor above.
406   template <typename U> void reset(U* array);
407   void reset(int disallow_reset_from_null);
408 
409   // Forbid comparison of scoped_ptr types.  If U != T, it totally
410   // doesn't make sense, and if U == T, it still doesn't make sense
411   // because you should never have the same object owned by two different
412   // scoped_ptrs.
413   template <class U> bool operator==(scoped_ptr<U> const& p2) const;
414   template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
415 };
416 
417 // Free functions
418 template <class T, class D>
419 void swap(scoped_ptr<T, D>& p1, scoped_ptr<T, D>& p2) {
420   p1.swap(p2);
421 }
422 
423 template <class T, class D>
424 bool operator==(T* p1, const scoped_ptr<T, D>& p2) {
425   return p1 == p2.get();
426 }
427 
428 template <class T, class D>
429 bool operator!=(T* p1, const scoped_ptr<T, D>& p2) {
430   return p1 != p2.get();
431 }
432 
433 // A function to convert T* into scoped_ptr<T>
434 // Doing e.g. make_scoped_ptr(new FooBarBaz<type>(arg)) is a shorter notation
435 // for scoped_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
436 template <typename T>
437 scoped_ptr<T> make_scoped_ptr(T* ptr) {
438   return scoped_ptr<T>(ptr);
439 }
440 
441 }  // namespace addressinput
442 }  // namespace i18n
443 
444 #endif  // I18N_ADDRESSINPUT_UTIL_SCOPED_PTR_H_
445