1 // Copyright 2013 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 // Scopers help you manage ownership of a pointer, helping you easily manage the
6 // a pointer within a scope, and automatically destroying the pointer at the
7 // end of a scope. There are two main classes you will use, which correspond
8 // to the operators new/delete and new[]/delete[].
10 // Example usage (scoped_ptr<T>):
12 // scoped_ptr<Foo> foo(new Foo("wee"));
13 // } // foo goes out of scope, releasing the pointer with it.
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.
29 // Example usage (scoped_ptr<T[]>):
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.
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:
44 // void TakesOwnership(scoped_ptr<Foo> arg) {
45 // // Do something with arg
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"));
52 // scoped_ptr<Foo> PassThru(scoped_ptr<Foo> arg) {
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 NULL.
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().
71 // Pass() properly handles upcast in initialization, i.e. you can use a
72 // scoped_ptr<Child> to initialize a scoped_ptr<Parent>:
74 // scoped_ptr<Foo> foo(new Foo());
75 // scoped_ptr<FooParent> parent(foo.Pass());
77 // PassAs<>() should be used to upcast return value in return statement:
79 // scoped_ptr<Foo> CreateFoo() {
80 // scoped_ptr<FooChild> result(new FooChild());
81 // return result.PassAs<Foo>();
84 // Note that PassAs<>() is implemented only for scoped_ptr<T>, but not for
85 // scoped_ptr<T[]>. This is because casting array pointers may not be safe.
87 // The original source code is from:
88 // http://src.chromium.org/chrome/trunk/src/base/memory/scoped_ptr.h?p=227789
90 // - no scoped_ptr_malloc
91 // - no compiler_specific.h include
92 // - namespaces are slightly rearranged
94 #ifndef I18N_ADDRESSINPUT_UTIL_INTERNAL_SCOPED_PTR_H_
95 #define I18N_ADDRESSINPUT_UTIL_INTERNAL_SCOPED_PTR_H_
97 // This is an implementation designed to match the anticipated future TR2
98 // implementation of the scoped_ptr class and scoped_ptr_malloc (deprecated).
104 #include <algorithm> // For std::swap().
106 #include "basictypes.h"
108 #include "template_util.h"
110 // NOTE: In Chromium, this is defined in base/compiler_specific.h. Here we
111 // just compile it out.
112 #define WARN_UNUSED_RESULT
115 namespace addressinput {
118 class RefCountedBase;
119 class RefCountedThreadSafeBase;
120 } // namespace subtle
122 // Function object which deletes its parameter, which must be a pointer.
123 // If C is an array type, invokes 'delete[]' on the parameter; otherwise,
124 // invokes 'delete'. The default deleter for scoped_ptr<T>.
126 struct DefaultDeleter {
128 template <typename U> DefaultDeleter(const DefaultDeleter<U>& other) {
129 // IMPLEMENTATION NOTE: C++11 20.7.1.1.2p2 only provides this constructor
130 // if U* is implicitly convertible to T* and U is not an array type.
132 // Correct implementation should use SFINAE to disable this
133 // constructor. However, since there are no other 1-argument constructors,
134 // using a COMPILE_ASSERT() based on is_convertible<> and requiring
135 // complete types is simpler and will cause compile failures for equivalent
138 // Note, the is_convertible<U*, T*> check also ensures that U is not an
139 // array. T is guaranteed to be a non-array, so any U* where U is an array
140 // cannot convert to T*.
141 enum { T_must_be_complete = sizeof(T) };
142 enum { U_must_be_complete = sizeof(U) };
143 COMPILE_ASSERT((is_convertible<U*, T*>::value),
144 U_ptr_must_implicitly_convert_to_T_ptr);
146 inline void operator()(T* ptr) const {
147 enum { type_must_be_complete = sizeof(T) };
152 // Specialization of DefaultDeleter for array types.
154 struct DefaultDeleter<T[]> {
155 inline void operator()(T* ptr) const {
156 enum { type_must_be_complete = sizeof(T) };
161 // Disable this operator for any U != T because it is undefined to execute
162 // an array delete when the static type of the array mismatches the dynamic
166 // C++98 [expr.delete]p3
167 // http://cplusplus.github.com/LWG/lwg-defects.html#938
168 template <typename U> void operator()(U* array) const;
171 template <class T, int n>
172 struct DefaultDeleter<T[n]> {
173 // Never allow someone to declare something like scoped_ptr<int[10]>.
174 COMPILE_ASSERT(sizeof(T) == -1, do_not_use_array_with_size_as_type);
177 // Function object which invokes 'free' on its parameter, which must be
178 // a pointer. Can be used to store malloc-allocated pointers in scoped_ptr:
180 // scoped_ptr<int, i18n::addressinput::FreeDeleter> foo_ptr(
181 // static_cast<int*>(malloc(sizeof(int))));
183 inline void operator()(void* ptr) const {
190 template <typename T> struct IsNotRefCounted {
192 value = !is_convertible<T*, subtle::RefCountedBase*>::value &&
193 !is_convertible<T*, subtle::RefCountedThreadSafeBase*>::
198 // Minimal implementation of the core logic of scoped_ptr, suitable for
199 // reuse in both scoped_ptr and its specializations.
200 template <class T, class D>
201 class scoped_ptr_impl {
203 explicit scoped_ptr_impl(T* p) : data_(p) { }
205 // Initializer for deleters that have data parameters.
206 scoped_ptr_impl(T* p, const D& d) : data_(p, d) {}
208 // Templated constructor that destructively takes the value from another
210 template <typename U, typename V>
211 scoped_ptr_impl(scoped_ptr_impl<U, V>* other)
212 : data_(other->release(), other->get_deleter()) {
213 // We do not support move-only deleters. We could modify our move
214 // emulation to have subtle::move() and subtle::forward()
215 // functions that are imperfect emulations of their C++11 equivalents,
216 // but until there's a requirement, just assume deleters are copyable.
219 template <typename U, typename V>
220 void TakeState(scoped_ptr_impl<U, V>* other) {
221 // See comment in templated constructor above regarding lack of support
222 // for move-only deleters.
223 reset(other->release());
224 get_deleter() = other->get_deleter();
228 if (data_.ptr != NULL) {
229 // Not using get_deleter() saves one function call in non-optimized
231 static_cast<D&>(data_)(data_.ptr);
236 // This is a self-reset, which is no longer allowed: http://crbug.com/162971
237 if (p != NULL && p == data_.ptr)
240 // Note that running data_.ptr = p can lead to undefined behavior if
241 // get_deleter()(get()) deletes this. In order to pevent this, reset()
242 // should update the stored pointer before deleting its old value.
244 // However, changing reset() to use that behavior may cause current code to
245 // break in unexpected ways. If the destruction of the owned object
246 // dereferences the scoped_ptr when it is destroyed by a call to reset(),
247 // then it will incorrectly dispatch calls to |p| rather than the original
248 // value of |data_.ptr|.
250 // During the transition period, set the stored pointer to NULL while
251 // deleting the object. Eventually, this safety check will be removed to
252 // prevent the scenario initially described from occuring and
253 // http://crbug.com/176091 can be closed.
257 static_cast<D&>(data_)(old);
261 T* get() const { return data_.ptr; }
263 D& get_deleter() { return data_; }
264 const D& get_deleter() const { return data_; }
266 void swap(scoped_ptr_impl& p2) {
267 // Standard swap idiom: 'using std::swap' ensures that std::swap is
268 // present in the overload set, but we call swap unqualified so that
269 // any more-specific overloads can be used, if available.
271 swap(static_cast<D&>(data_), static_cast<D&>(p2.data_));
272 swap(data_.ptr, p2.data_.ptr);
276 T* old_ptr = data_.ptr;
282 // Needed to allow type-converting constructor.
283 template <typename U, typename V> friend class scoped_ptr_impl;
285 // Use the empty base class optimization to allow us to have a D
286 // member, while avoiding any space overhead for it when D is an
287 // empty class. See e.g. http://www.cantrip.org/emptyopt.html for a good
288 // discussion of this technique.
289 struct Data : public D {
290 explicit Data(T* ptr_in) : ptr(ptr_in) {}
291 Data(T* ptr_in, const D& other) : D(other), ptr(ptr_in) {}
297 DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl);
300 } // namespace internal
302 } // namespace addressinput
305 // A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
306 // automatically deletes the pointer it holds (if any).
307 // That is, scoped_ptr<T> owns the T object that it points to.
308 // Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object.
309 // Also like T*, scoped_ptr<T> is thread-compatible, and once you
310 // dereference it, you get the thread safety guarantees of T.
312 // The size of scoped_ptr is small. On most compilers, when using the
313 // DefaultDeleter, sizeof(scoped_ptr<T>) == sizeof(T*). Custom deleters will
314 // increase the size proportional to whatever state they need to have. See
315 // comments inside scoped_ptr_impl<> for details.
317 // Current implementation targets having a strict subset of C++11's
318 // unique_ptr<> features. Known deficiencies include not supporting move-only
319 // deleteres, function pointers as deleters, and deleters with reference
321 template <class T, class D = i18n::addressinput::DefaultDeleter<T> >
323 MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue)
325 COMPILE_ASSERT(i18n::addressinput::internal::IsNotRefCounted<T>::value,
326 T_is_refcounted_type_and_needs_scoped_refptr);
329 // The element and deleter types.
330 typedef T element_type;
331 typedef D deleter_type;
333 // Constructor. Defaults to initializing with NULL.
334 scoped_ptr() : impl_(NULL) { }
336 // Constructor. Takes ownership of p.
337 explicit scoped_ptr(element_type* p) : impl_(p) { }
339 // Constructor. Allows initialization of a stateful deleter.
340 scoped_ptr(element_type* p, const D& d) : impl_(p, d) { }
342 // Constructor. Allows construction from a scoped_ptr rvalue for a
343 // convertible type and deleter.
345 // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this constructor distinct
346 // from the normal move constructor. By C++11 20.7.1.2.1.21, this constructor
347 // has different post-conditions if D is a reference type. Since this
348 // implementation does not support deleters with reference type,
349 // we do not need a separate move constructor allowing us to avoid one
350 // use of SFINAE. You only need to care about this if you modify the
351 // implementation of scoped_ptr.
352 template <typename U, typename V>
353 scoped_ptr(scoped_ptr<U, V> other) : impl_(&other.impl_) {
354 COMPILE_ASSERT(!is_array<U>::value, U_cannot_be_an_array);
357 // Constructor. Move constructor for C++03 move emulation of this type.
358 scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { }
360 // operator=. Allows assignment from a scoped_ptr rvalue for a convertible
363 // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this operator= distinct from
364 // the normal move assignment operator. By C++11 20.7.1.2.3.4, this templated
365 // form has different requirements on for move-only Deleters. Since this
366 // implementation does not support move-only Deleters, we do not need a
367 // separate move assignment operator allowing us to avoid one use of SFINAE.
368 // You only need to care about this if you modify the implementation of
370 template <typename U, typename V>
371 scoped_ptr& operator=(scoped_ptr<U, V> rhs) {
372 COMPILE_ASSERT(!is_array<U>::value, U_cannot_be_an_array);
373 impl_.TakeState(&rhs.impl_);
377 // Reset. Deletes the currently owned object, if any.
378 // Then takes ownership of a new object, if given.
379 void reset(element_type* p = NULL) { impl_.reset(p); }
381 // Accessors to get the owned object.
382 // operator* and operator-> will assert() if there is no current object.
383 element_type& operator*() const {
384 assert(impl_.get() != NULL);
387 element_type* operator->() const {
388 assert(impl_.get() != NULL);
391 element_type* get() const { return impl_.get(); }
393 // Access to the deleter.
394 deleter_type& get_deleter() { return impl_.get_deleter(); }
395 const deleter_type& get_deleter() const { return impl_.get_deleter(); }
397 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
398 // implicitly convertible to a real bool (which is dangerous).
400 // Note that this trick is only safe when the == and != operators
401 // are declared explicitly, as otherwise "scoped_ptr1 ==
402 // scoped_ptr2" will compile but do the wrong thing (i.e., convert
403 // to Testable and then do the comparison).
406 i18n::addressinput::internal::scoped_ptr_impl <element_type, deleter_type>
407 scoped_ptr::*Testable;
410 operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; }
412 // Comparison operators.
413 // These return whether two scoped_ptr refer to the same object, not just to
414 // two different but equal objects.
415 bool operator==(const element_type* p) const { return impl_.get() == p; }
416 bool operator!=(const element_type* p) const { return impl_.get() != p; }
418 // Swap two scoped pointers.
419 void swap(scoped_ptr& p2) {
420 impl_.swap(p2.impl_);
423 // Release a pointer.
424 // The return value is the current pointer held by this object.
425 // If this object holds a NULL pointer, the return value is NULL.
426 // After this operation, this object will hold a NULL pointer,
427 // and will not own the object any more.
428 element_type* release() WARN_UNUSED_RESULT {
429 return impl_.release();
432 // C++98 doesn't support functions templates with default parameters which
433 // makes it hard to write a PassAs() that understands converting the deleter
434 // while preserving simple calling semantics.
436 // Until there is a use case for PassAs() with custom deleters, just ignore
437 // the custom deleter.
438 template <typename PassAsType>
439 scoped_ptr<PassAsType> PassAs() {
440 return scoped_ptr<PassAsType>(Pass());
444 // Needed to reach into |impl_| in the constructor.
445 template <typename U, typename V> friend class scoped_ptr;
446 i18n::addressinput::internal::scoped_ptr_impl<element_type, deleter_type>
449 // Forbidden for API compatibility with std::unique_ptr.
450 explicit scoped_ptr(int disallow_construction_from_null);
452 // Forbid comparison of scoped_ptr types. If U != T, it totally
453 // doesn't make sense, and if U == T, it still doesn't make sense
454 // because you should never have the same object owned by two different
456 template <class U> bool operator==(scoped_ptr<U> const& p2) const;
457 template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
460 template <class T, class D>
461 class scoped_ptr<T[], D> {
462 MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue)
465 // The element and deleter types.
466 typedef T element_type;
467 typedef D deleter_type;
469 // Constructor. Defaults to initializing with NULL.
470 scoped_ptr() : impl_(NULL) { }
472 // Constructor. Stores the given array. Note that the argument's type
473 // must exactly match T*. In particular:
474 // - it cannot be a pointer to a type derived from T, because it is
475 // inherently unsafe in the general case to access an array through a
476 // pointer whose dynamic type does not match its static type (eg., if
477 // T and the derived types had different sizes access would be
478 // incorrectly calculated). Deletion is also always undefined
479 // (C++98 [expr.delete]p3). If you're doing this, fix your code.
480 // - it cannot be NULL, because NULL is an integral expression, not a
481 // pointer to T. Use the no-argument version instead of explicitly
483 // - it cannot be const-qualified differently from T per unique_ptr spec
484 // (http://cplusplus.github.com/LWG/lwg-active.html#2118). Users wanting
485 // to work around this may use implicit_cast<const T*>().
486 // However, because of the first bullet in this comment, users MUST
487 // NOT use implicit_cast<Base*>() to upcast the static type of the array.
488 explicit scoped_ptr(element_type* array) : impl_(array) { }
490 // Constructor. Move constructor for C++03 move emulation of this type.
491 scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { }
493 // operator=. Move operator= for C++03 move emulation of this type.
494 scoped_ptr& operator=(RValue rhs) {
495 impl_.TakeState(&rhs.object->impl_);
499 // Reset. Deletes the currently owned array, if any.
500 // Then takes ownership of a new object, if given.
501 void reset(element_type* array = NULL) { impl_.reset(array); }
503 // Accessors to get the owned array.
504 element_type& operator[](size_t i) const {
505 assert(impl_.get() != NULL);
506 return impl_.get()[i];
508 element_type* get() const { return impl_.get(); }
510 // Access to the deleter.
511 deleter_type& get_deleter() { return impl_.get_deleter(); }
512 const deleter_type& get_deleter() const { return impl_.get_deleter(); }
514 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
515 // implicitly convertible to a real bool (which is dangerous).
518 i18n::addressinput::internal::scoped_ptr_impl<element_type, deleter_type>
519 scoped_ptr::*Testable;
522 operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; }
524 // Comparison operators.
525 // These return whether two scoped_ptr refer to the same object, not just to
526 // two different but equal objects.
527 bool operator==(element_type* array) const { return impl_.get() == array; }
528 bool operator!=(element_type* array) const { return impl_.get() != array; }
530 // Swap two scoped pointers.
531 void swap(scoped_ptr& p2) {
532 impl_.swap(p2.impl_);
535 // Release a pointer.
536 // The return value is the current pointer held by this object.
537 // If this object holds a NULL pointer, the return value is NULL.
538 // After this operation, this object will hold a NULL pointer,
539 // and will not own the object any more.
540 element_type* release() WARN_UNUSED_RESULT {
541 return impl_.release();
545 // Force element_type to be a complete type.
546 enum { type_must_be_complete = sizeof(element_type) };
548 // Actually hold the data.
549 i18n::addressinput::internal::scoped_ptr_impl<element_type, deleter_type>
552 // Disable initialization from any type other than element_type*, by
553 // providing a constructor that matches such an initialization, but is
554 // private and has no definition. This is disabled because it is not safe to
555 // call delete[] on an array whose static type does not match its dynamic
557 template <typename U> explicit scoped_ptr(U* array);
558 explicit scoped_ptr(int disallow_construction_from_null);
560 // Disable reset() from any type other than element_type*, for the same
561 // reasons as the constructor above.
562 template <typename U> void reset(U* array);
563 void reset(int disallow_reset_from_null);
565 // Forbid comparison of scoped_ptr types. If U != T, it totally
566 // doesn't make sense, and if U == T, it still doesn't make sense
567 // because you should never have the same object owned by two different
569 template <class U> bool operator==(scoped_ptr<U> const& p2) const;
570 template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
574 template <class T, class D>
575 void swap(scoped_ptr<T, D>& p1, scoped_ptr<T, D>& p2) {
579 template <class T, class D>
580 bool operator==(T* p1, const scoped_ptr<T, D>& p2) {
581 return p1 == p2.get();
584 template <class T, class D>
585 bool operator!=(T* p1, const scoped_ptr<T, D>& p2) {
586 return p1 != p2.get();
589 // A function to convert T* into scoped_ptr<T>
590 // Doing e.g. make_scoped_ptr(new FooBarBaz<type>(arg)) is a shorter notation
591 // for scoped_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
592 template <typename T>
593 scoped_ptr<T> make_scoped_ptr(T* ptr) {
594 return scoped_ptr<T>(ptr);
597 #endif // I18N_ADDRESSINPUT_UTIL_INTERNAL_SCOPED_PTR_H_