Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / base / memory / scoped_ptr.h
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 // Scopers help you manage ownership of a pointer, helping you easily manage a
6 // pointer within a scope, and automatically destroying the pointer at the end
7 // of a scope.  There are two main classes you will use, which correspond to the
8 // operators new/delete and new[]/delete[].
9 //
10 // Example usage (scoped_ptr<T>):
11 //   {
12 //     scoped_ptr<Foo> foo(new Foo("wee"));
13 //   }  // foo goes out of scope, releasing the pointer with it.
14 //
15 //   {
16 //     scoped_ptr<Foo> foo;          // No pointer managed.
17 //     foo.reset(new Foo("wee"));    // Now a pointer is managed.
18 //     foo.reset(new Foo("wee2"));   // Foo("wee") was destroyed.
19 //     foo.reset(new Foo("wee3"));   // Foo("wee2") was destroyed.
20 //     foo->Method();                // Foo::Method() called.
21 //     foo.get()->Method();          // Foo::Method() called.
22 //     SomeFunc(foo.release());      // SomeFunc takes ownership, foo no longer
23 //                                   // manages a pointer.
24 //     foo.reset(new Foo("wee4"));   // foo manages a pointer again.
25 //     foo.reset();                  // Foo("wee4") destroyed, foo no longer
26 //                                   // manages a pointer.
27 //   }  // foo wasn't managing a pointer, so nothing was destroyed.
28 //
29 // Example usage (scoped_ptr<T[]>):
30 //   {
31 //     scoped_ptr<Foo[]> foo(new Foo[100]);
32 //     foo.get()->Method();  // Foo::Method on the 0th element.
33 //     foo[10].Method();     // Foo::Method on the 10th element.
34 //   }
35 //
36 // These scopers also implement part of the functionality of C++11 unique_ptr
37 // in that they are "movable but not copyable."  You can use the scopers in
38 // the parameter and return types of functions to signify ownership transfer
39 // in to and out of a function.  When calling a function that has a scoper
40 // as the argument type, it must be called with the result of an analogous
41 // scoper's Pass() function or another function that generates a temporary;
42 // passing by copy will NOT work.  Here is an example using scoped_ptr:
43 //
44 //   void TakesOwnership(scoped_ptr<Foo> arg) {
45 //     // Do something with arg
46 //   }
47 //   scoped_ptr<Foo> CreateFoo() {
48 //     // No need for calling Pass() because we are constructing a temporary
49 //     // for the return value.
50 //     return scoped_ptr<Foo>(new Foo("new"));
51 //   }
52 //   scoped_ptr<Foo> PassThru(scoped_ptr<Foo> arg) {
53 //     return arg.Pass();
54 //   }
55 //
56 //   {
57 //     scoped_ptr<Foo> ptr(new Foo("yay"));  // ptr manages Foo("yay").
58 //     TakesOwnership(ptr.Pass());           // ptr no longer owns Foo("yay").
59 //     scoped_ptr<Foo> ptr2 = CreateFoo();   // ptr2 owns the return Foo.
60 //     scoped_ptr<Foo> ptr3 =                // ptr3 now owns what was in ptr2.
61 //         PassThru(ptr2.Pass());            // ptr2 is correspondingly nullptr.
62 //   }
63 //
64 // Notice that if you do not call Pass() when returning from PassThru(), or
65 // when invoking TakesOwnership(), the code will not compile because scopers
66 // are not copyable; they only implement move semantics which require calling
67 // the Pass() function to signify a destructive transfer of state. CreateFoo()
68 // is different though because we are constructing a temporary on the return
69 // line and thus can avoid needing to call Pass().
70 //
71 // Pass() properly handles upcast in initialization, i.e. you can use a
72 // scoped_ptr<Child> to initialize a scoped_ptr<Parent>:
73 //
74 //   scoped_ptr<Foo> foo(new Foo());
75 //   scoped_ptr<FooParent> parent(foo.Pass());
76
77 #ifndef BASE_MEMORY_SCOPED_PTR_H_
78 #define BASE_MEMORY_SCOPED_PTR_H_
79
80 // This is an implementation designed to match the anticipated future TR2
81 // implementation of the scoped_ptr class.
82
83 #include <assert.h>
84 #include <stddef.h>
85 #include <stdlib.h>
86
87 #include <algorithm>  // For std::swap().
88
89 #include "base/basictypes.h"
90 #include "base/compiler_specific.h"
91 #include "base/move.h"
92 #include "base/template_util.h"
93
94 namespace base {
95
96 namespace subtle {
97 class RefCountedBase;
98 class RefCountedThreadSafeBase;
99 }  // namespace subtle
100
101 // Function object which deletes its parameter, which must be a pointer.
102 // If C is an array type, invokes 'delete[]' on the parameter; otherwise,
103 // invokes 'delete'. The default deleter for scoped_ptr<T>.
104 template <class T>
105 struct DefaultDeleter {
106   DefaultDeleter() {}
107   template <typename U> DefaultDeleter(const DefaultDeleter<U>& other) {
108     // IMPLEMENTATION NOTE: C++11 20.7.1.1.2p2 only provides this constructor
109     // if U* is implicitly convertible to T* and U is not an array type.
110     //
111     // Correct implementation should use SFINAE to disable this
112     // constructor. However, since there are no other 1-argument constructors,
113     // using a COMPILE_ASSERT() based on is_convertible<> and requiring
114     // complete types is simpler and will cause compile failures for equivalent
115     // misuses.
116     //
117     // Note, the is_convertible<U*, T*> check also ensures that U is not an
118     // array. T is guaranteed to be a non-array, so any U* where U is an array
119     // cannot convert to T*.
120     enum { T_must_be_complete = sizeof(T) };
121     enum { U_must_be_complete = sizeof(U) };
122     COMPILE_ASSERT((base::is_convertible<U*, T*>::value),
123                    U_ptr_must_implicitly_convert_to_T_ptr);
124   }
125   inline void operator()(T* ptr) const {
126     enum { type_must_be_complete = sizeof(T) };
127     delete ptr;
128   }
129 };
130
131 // Specialization of DefaultDeleter for array types.
132 template <class T>
133 struct DefaultDeleter<T[]> {
134   inline void operator()(T* ptr) const {
135     enum { type_must_be_complete = sizeof(T) };
136     delete[] ptr;
137   }
138
139  private:
140   // Disable this operator for any U != T because it is undefined to execute
141   // an array delete when the static type of the array mismatches the dynamic
142   // type.
143   //
144   // References:
145   //   C++98 [expr.delete]p3
146   //   http://cplusplus.github.com/LWG/lwg-defects.html#938
147   template <typename U> void operator()(U* array) const;
148 };
149
150 template <class T, int n>
151 struct DefaultDeleter<T[n]> {
152   // Never allow someone to declare something like scoped_ptr<int[10]>.
153   COMPILE_ASSERT(sizeof(T) == -1, do_not_use_array_with_size_as_type);
154 };
155
156 // Function object which invokes 'free' on its parameter, which must be
157 // a pointer. Can be used to store malloc-allocated pointers in scoped_ptr:
158 //
159 // scoped_ptr<int, base::FreeDeleter> foo_ptr(
160 //     static_cast<int*>(malloc(sizeof(int))));
161 struct FreeDeleter {
162   inline void operator()(void* ptr) const {
163     free(ptr);
164   }
165 };
166
167 namespace internal {
168
169 template <typename T> struct IsNotRefCounted {
170   enum {
171     value = !base::is_convertible<T*, base::subtle::RefCountedBase*>::value &&
172         !base::is_convertible<T*, base::subtle::RefCountedThreadSafeBase*>::
173             value
174   };
175 };
176
177 template <typename T>
178 struct ShouldAbortOnSelfReset {
179   template <typename U>
180   static NoType Test(const typename U::AllowSelfReset*);
181
182   template <typename U>
183   static YesType Test(...);
184
185   static const bool value = sizeof(Test<T>(0)) == sizeof(YesType);
186 };
187
188 // Minimal implementation of the core logic of scoped_ptr, suitable for
189 // reuse in both scoped_ptr and its specializations.
190 template <class T, class D>
191 class scoped_ptr_impl {
192  public:
193   explicit scoped_ptr_impl(T* p) : data_(p) {}
194
195   // Initializer for deleters that have data parameters.
196   scoped_ptr_impl(T* p, const D& d) : data_(p, d) {}
197
198   // Templated constructor that destructively takes the value from another
199   // scoped_ptr_impl.
200   template <typename U, typename V>
201   scoped_ptr_impl(scoped_ptr_impl<U, V>* other)
202       : data_(other->release(), other->get_deleter()) {
203     // We do not support move-only deleters.  We could modify our move
204     // emulation to have base::subtle::move() and base::subtle::forward()
205     // functions that are imperfect emulations of their C++11 equivalents,
206     // but until there's a requirement, just assume deleters are copyable.
207   }
208
209   template <typename U, typename V>
210   void TakeState(scoped_ptr_impl<U, V>* other) {
211     // See comment in templated constructor above regarding lack of support
212     // for move-only deleters.
213     reset(other->release());
214     get_deleter() = other->get_deleter();
215   }
216
217   ~scoped_ptr_impl() {
218     if (data_.ptr != nullptr) {
219       // Not using get_deleter() saves one function call in non-optimized
220       // builds.
221       static_cast<D&>(data_)(data_.ptr);
222     }
223   }
224
225   void reset(T* p) {
226     // This is a self-reset, which is no longer allowed for default deleters:
227     // https://crbug.com/162971
228     assert(!ShouldAbortOnSelfReset<D>::value || p == nullptr || p != data_.ptr);
229
230     // Note that running data_.ptr = p can lead to undefined behavior if
231     // get_deleter()(get()) deletes this. In order to prevent this, reset()
232     // should update the stored pointer before deleting its old value.
233     //
234     // However, changing reset() to use that behavior may cause current code to
235     // break in unexpected ways. If the destruction of the owned object
236     // dereferences the scoped_ptr when it is destroyed by a call to reset(),
237     // then it will incorrectly dispatch calls to |p| rather than the original
238     // value of |data_.ptr|.
239     //
240     // During the transition period, set the stored pointer to nullptr while
241     // deleting the object. Eventually, this safety check will be removed to
242     // prevent the scenario initially described from occuring and
243     // http://crbug.com/176091 can be closed.
244     T* old = data_.ptr;
245     data_.ptr = nullptr;
246     if (old != nullptr)
247       static_cast<D&>(data_)(old);
248     data_.ptr = p;
249   }
250
251   T* get() const { return data_.ptr; }
252
253   D& get_deleter() { return data_; }
254   const D& get_deleter() const { return data_; }
255
256   void swap(scoped_ptr_impl& p2) {
257     // Standard swap idiom: 'using std::swap' ensures that std::swap is
258     // present in the overload set, but we call swap unqualified so that
259     // any more-specific overloads can be used, if available.
260     using std::swap;
261     swap(static_cast<D&>(data_), static_cast<D&>(p2.data_));
262     swap(data_.ptr, p2.data_.ptr);
263   }
264
265   T* release() {
266     T* old_ptr = data_.ptr;
267     data_.ptr = nullptr;
268     return old_ptr;
269   }
270
271  private:
272   // Needed to allow type-converting constructor.
273   template <typename U, typename V> friend class scoped_ptr_impl;
274
275   // Use the empty base class optimization to allow us to have a D
276   // member, while avoiding any space overhead for it when D is an
277   // empty class.  See e.g. http://www.cantrip.org/emptyopt.html for a good
278   // discussion of this technique.
279   struct Data : public D {
280     explicit Data(T* ptr_in) : ptr(ptr_in) {}
281     Data(T* ptr_in, const D& other) : D(other), ptr(ptr_in) {}
282     T* ptr;
283   };
284
285   Data data_;
286
287   DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl);
288 };
289
290 }  // namespace internal
291
292 }  // namespace base
293
294 // A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
295 // automatically deletes the pointer it holds (if any).
296 // That is, scoped_ptr<T> owns the T object that it points to.
297 // Like a T*, a scoped_ptr<T> may hold either nullptr or a pointer to a T
298 // object. Also like T*, scoped_ptr<T> is thread-compatible, and once you
299 // dereference it, you get the thread safety guarantees of T.
300 //
301 // The size of scoped_ptr is small. On most compilers, when using the
302 // DefaultDeleter, sizeof(scoped_ptr<T>) == sizeof(T*). Custom deleters will
303 // increase the size proportional to whatever state they need to have. See
304 // comments inside scoped_ptr_impl<> for details.
305 //
306 // Current implementation targets having a strict subset of  C++11's
307 // unique_ptr<> features. Known deficiencies include not supporting move-only
308 // deleteres, function pointers as deleters, and deleters with reference
309 // types.
310 template <class T, class D = base::DefaultDeleter<T> >
311 class scoped_ptr {
312   MOVE_ONLY_TYPE_WITH_MOVE_CONSTRUCTOR_FOR_CPP_03(scoped_ptr)
313
314   COMPILE_ASSERT(base::internal::IsNotRefCounted<T>::value,
315                  T_is_refcounted_type_and_needs_scoped_refptr);
316
317  public:
318   // The element and deleter types.
319   typedef T element_type;
320   typedef D deleter_type;
321
322   // Constructor.  Defaults to initializing with nullptr.
323   scoped_ptr() : impl_(nullptr) {}
324
325   // Constructor.  Takes ownership of p.
326   explicit scoped_ptr(element_type* p) : impl_(p) {}
327
328   // Constructor.  Allows initialization of a stateful deleter.
329   scoped_ptr(element_type* p, const D& d) : impl_(p, d) {}
330
331   // Constructor.  Allows construction from a nullptr.
332   scoped_ptr(decltype(nullptr)) : impl_(nullptr) {}
333
334   // Constructor.  Allows construction from a scoped_ptr rvalue for a
335   // convertible type and deleter.
336   //
337   // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this constructor distinct
338   // from the normal move constructor. By C++11 20.7.1.2.1.21, this constructor
339   // has different post-conditions if D is a reference type. Since this
340   // implementation does not support deleters with reference type,
341   // we do not need a separate move constructor allowing us to avoid one
342   // use of SFINAE. You only need to care about this if you modify the
343   // implementation of scoped_ptr.
344   template <typename U, typename V>
345   scoped_ptr(scoped_ptr<U, V>&& other)
346       : impl_(&other.impl_) {
347     COMPILE_ASSERT(!base::is_array<U>::value, U_cannot_be_an_array);
348   }
349
350   // operator=.  Allows assignment from a scoped_ptr rvalue for a convertible
351   // type and deleter.
352   //
353   // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this operator= distinct from
354   // the normal move assignment operator. By C++11 20.7.1.2.3.4, this templated
355   // form has different requirements on for move-only Deleters. Since this
356   // implementation does not support move-only Deleters, we do not need a
357   // separate move assignment operator allowing us to avoid one use of SFINAE.
358   // You only need to care about this if you modify the implementation of
359   // scoped_ptr.
360   template <typename U, typename V>
361   scoped_ptr& operator=(scoped_ptr<U, V>&& rhs) {
362     COMPILE_ASSERT(!base::is_array<U>::value, U_cannot_be_an_array);
363     impl_.TakeState(&rhs.impl_);
364     return *this;
365   }
366
367   // operator=.  Allows assignment from a nullptr. Deletes the currently owned
368   // object, if any.
369   scoped_ptr& operator=(decltype(nullptr)) {
370     reset();
371     return *this;
372   }
373
374   // Reset.  Deletes the currently owned object, if any.
375   // Then takes ownership of a new object, if given.
376   void reset(element_type* p = nullptr) { impl_.reset(p); }
377
378   // Accessors to get the owned object.
379   // operator* and operator-> will assert() if there is no current object.
380   element_type& operator*() const {
381     assert(impl_.get() != nullptr);
382     return *impl_.get();
383   }
384   element_type* operator->() const  {
385     assert(impl_.get() != nullptr);
386     return impl_.get();
387   }
388   element_type* get() const { return impl_.get(); }
389
390   // Access to the deleter.
391   deleter_type& get_deleter() { return impl_.get_deleter(); }
392   const deleter_type& get_deleter() const { return impl_.get_deleter(); }
393
394   // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
395   // implicitly convertible to a real bool (which is dangerous).
396   //
397   // Note that this trick is only safe when the == and != operators
398   // are declared explicitly, as otherwise "scoped_ptr1 ==
399   // scoped_ptr2" will compile but do the wrong thing (i.e., convert
400   // to Testable and then do the comparison).
401  private:
402   typedef base::internal::scoped_ptr_impl<element_type, deleter_type>
403       scoped_ptr::*Testable;
404
405  public:
406   operator Testable() const {
407     return impl_.get() ? &scoped_ptr::impl_ : nullptr;
408   }
409
410   // Comparison operators.
411   // These return whether two scoped_ptr refer to the same object, not just to
412   // two different but equal objects.
413   bool operator==(const element_type* p) const { return impl_.get() == p; }
414   bool operator!=(const element_type* p) const { return impl_.get() != p; }
415
416   // Swap two scoped pointers.
417   void swap(scoped_ptr& p2) {
418     impl_.swap(p2.impl_);
419   }
420
421   // Release a pointer.
422   // The return value is the current pointer held by this object. If this object
423   // holds a nullptr, the return value is nullptr. After this operation, this
424   // object will hold a nullptr, and will not own the object any more.
425   element_type* release() WARN_UNUSED_RESULT {
426     return impl_.release();
427   }
428
429  private:
430   // Needed to reach into |impl_| in the constructor.
431   template <typename U, typename V> friend class scoped_ptr;
432   base::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
433
434   // Forbidden for API compatibility with std::unique_ptr.
435   explicit scoped_ptr(int disallow_construction_from_null);
436
437   // Forbid comparison of scoped_ptr types.  If U != T, it totally
438   // doesn't make sense, and if U == T, it still doesn't make sense
439   // because you should never have the same object owned by two different
440   // scoped_ptrs.
441   template <class U> bool operator==(scoped_ptr<U> const& p2) const;
442   template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
443 };
444
445 template <class T, class D>
446 class scoped_ptr<T[], D> {
447   MOVE_ONLY_TYPE_WITH_MOVE_CONSTRUCTOR_FOR_CPP_03(scoped_ptr)
448
449  public:
450   // The element and deleter types.
451   typedef T element_type;
452   typedef D deleter_type;
453
454   // Constructor.  Defaults to initializing with nullptr.
455   scoped_ptr() : impl_(nullptr) {}
456
457   // Constructor. Stores the given array. Note that the argument's type
458   // must exactly match T*. In particular:
459   // - it cannot be a pointer to a type derived from T, because it is
460   //   inherently unsafe in the general case to access an array through a
461   //   pointer whose dynamic type does not match its static type (eg., if
462   //   T and the derived types had different sizes access would be
463   //   incorrectly calculated). Deletion is also always undefined
464   //   (C++98 [expr.delete]p3). If you're doing this, fix your code.
465   // - it cannot be const-qualified differently from T per unique_ptr spec
466   //   (http://cplusplus.github.com/LWG/lwg-active.html#2118). Users wanting
467   //   to work around this may use implicit_cast<const T*>().
468   //   However, because of the first bullet in this comment, users MUST
469   //   NOT use implicit_cast<Base*>() to upcast the static type of the array.
470   explicit scoped_ptr(element_type* array) : impl_(array) {}
471
472   // Constructor.  Allows construction from a nullptr.
473   scoped_ptr(decltype(nullptr)) : impl_(nullptr) {}
474
475   // Constructor.  Allows construction from a scoped_ptr rvalue.
476   scoped_ptr(scoped_ptr&& other) : impl_(&other.impl_) {}
477
478   // operator=.  Allows assignment from a scoped_ptr rvalue.
479   scoped_ptr& operator=(scoped_ptr&& rhs) {
480     impl_.TakeState(&rhs.impl_);
481     return *this;
482   }
483
484   // operator=.  Allows assignment from a nullptr. Deletes the currently owned
485   // array, if any.
486   scoped_ptr& operator=(decltype(nullptr)) {
487     reset();
488     return *this;
489   }
490
491   // Reset.  Deletes the currently owned array, if any.
492   // Then takes ownership of a new object, if given.
493   void reset(element_type* array = nullptr) { impl_.reset(array); }
494
495   // Accessors to get the owned array.
496   element_type& operator[](size_t i) const {
497     assert(impl_.get() != nullptr);
498     return impl_.get()[i];
499   }
500   element_type* get() const { return impl_.get(); }
501
502   // Access to the deleter.
503   deleter_type& get_deleter() { return impl_.get_deleter(); }
504   const deleter_type& get_deleter() const { return impl_.get_deleter(); }
505
506   // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
507   // implicitly convertible to a real bool (which is dangerous).
508  private:
509   typedef base::internal::scoped_ptr_impl<element_type, deleter_type>
510       scoped_ptr::*Testable;
511
512  public:
513   operator Testable() const {
514     return impl_.get() ? &scoped_ptr::impl_ : nullptr;
515   }
516
517   // Comparison operators.
518   // These return whether two scoped_ptr refer to the same object, not just to
519   // two different but equal objects.
520   bool operator==(element_type* array) const { return impl_.get() == array; }
521   bool operator!=(element_type* array) const { return impl_.get() != array; }
522
523   // Swap two scoped pointers.
524   void swap(scoped_ptr& p2) {
525     impl_.swap(p2.impl_);
526   }
527
528   // Release a pointer.
529   // The return value is the current pointer held by this object. If this object
530   // holds a nullptr, the return value is nullptr. After this operation, this
531   // object will hold a nullptr, and will not own the object any more.
532   element_type* release() WARN_UNUSED_RESULT {
533     return impl_.release();
534   }
535
536  private:
537   // Force element_type to be a complete type.
538   enum { type_must_be_complete = sizeof(element_type) };
539
540   // Actually hold the data.
541   base::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
542
543   // Disable initialization from any type other than element_type*, by
544   // providing a constructor that matches such an initialization, but is
545   // private and has no definition. This is disabled because it is not safe to
546   // call delete[] on an array whose static type does not match its dynamic
547   // type.
548   template <typename U> explicit scoped_ptr(U* array);
549   explicit scoped_ptr(int disallow_construction_from_null);
550
551   // Disable reset() from any type other than element_type*, for the same
552   // reasons as the constructor above.
553   template <typename U> void reset(U* array);
554   void reset(int disallow_reset_from_null);
555
556   // Forbid comparison of scoped_ptr types.  If U != T, it totally
557   // doesn't make sense, and if U == T, it still doesn't make sense
558   // because you should never have the same object owned by two different
559   // scoped_ptrs.
560   template <class U> bool operator==(scoped_ptr<U> const& p2) const;
561   template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
562 };
563
564 // Free functions
565 template <class T, class D>
566 void swap(scoped_ptr<T, D>& p1, scoped_ptr<T, D>& p2) {
567   p1.swap(p2);
568 }
569
570 template <class T, class D>
571 bool operator==(T* p1, const scoped_ptr<T, D>& p2) {
572   return p1 == p2.get();
573 }
574
575 template <class T, class D>
576 bool operator!=(T* p1, const scoped_ptr<T, D>& p2) {
577   return p1 != p2.get();
578 }
579
580 // A function to convert T* into scoped_ptr<T>
581 // Doing e.g. make_scoped_ptr(new FooBarBaz<type>(arg)) is a shorter notation
582 // for scoped_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
583 template <typename T>
584 scoped_ptr<T> make_scoped_ptr(T* ptr) {
585   return scoped_ptr<T>(ptr);
586 }
587
588 #endif  // BASE_MEMORY_SCOPED_PTR_H_