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.
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[].
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 nullptr.
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 #ifndef BASE_MEMORY_SCOPED_PTR_H_
78 #define BASE_MEMORY_SCOPED_PTR_H_
80 // This is an implementation designed to match the anticipated future TR2
81 // implementation of the scoped_ptr class.
87 #include <algorithm> // For std::swap().
90 #include "base/basictypes.h"
91 #include "base/compiler_specific.h"
92 #include "base/move.h"
93 #include "base/template_util.h"
99 class RefCountedThreadSafeBase
;
100 } // namespace subtle
102 // Function object which deletes its parameter, which must be a pointer.
103 // If C is an array type, invokes 'delete[]' on the parameter; otherwise,
104 // invokes 'delete'. The default deleter for scoped_ptr<T>.
106 struct DefaultDeleter
{
108 template <typename U
> DefaultDeleter(const DefaultDeleter
<U
>& other
) {
109 // IMPLEMENTATION NOTE: C++11 20.7.1.1.2p2 only provides this constructor
110 // if U* is implicitly convertible to T* and U is not an array type.
112 // Correct implementation should use SFINAE to disable this
113 // constructor. However, since there are no other 1-argument constructors,
114 // using a COMPILE_ASSERT() based on is_convertible<> and requiring
115 // complete types is simpler and will cause compile failures for equivalent
118 // Note, the is_convertible<U*, T*> check also ensures that U is not an
119 // array. T is guaranteed to be a non-array, so any U* where U is an array
120 // cannot convert to T*.
121 enum { T_must_be_complete
= sizeof(T
) };
122 enum { U_must_be_complete
= sizeof(U
) };
123 COMPILE_ASSERT((base::is_convertible
<U
*, T
*>::value
),
124 U_ptr_must_implicitly_convert_to_T_ptr
);
126 inline void operator()(T
* ptr
) const {
127 enum { type_must_be_complete
= sizeof(T
) };
132 // Specialization of DefaultDeleter for array types.
134 struct DefaultDeleter
<T
[]> {
135 inline void operator()(T
* ptr
) const {
136 enum { type_must_be_complete
= sizeof(T
) };
141 // Disable this operator for any U != T because it is undefined to execute
142 // an array delete when the static type of the array mismatches the dynamic
146 // C++98 [expr.delete]p3
147 // http://cplusplus.github.com/LWG/lwg-defects.html#938
148 template <typename U
> void operator()(U
* array
) const;
151 template <class T
, int n
>
152 struct DefaultDeleter
<T
[n
]> {
153 // Never allow someone to declare something like scoped_ptr<int[10]>.
154 COMPILE_ASSERT(sizeof(T
) == -1, do_not_use_array_with_size_as_type
);
157 // Function object which invokes 'free' on its parameter, which must be
158 // a pointer. Can be used to store malloc-allocated pointers in scoped_ptr:
160 // scoped_ptr<int, base::FreeDeleter> foo_ptr(
161 // static_cast<int*>(malloc(sizeof(int))));
163 inline void operator()(void* ptr
) const {
170 template <typename T
> struct IsNotRefCounted
{
172 value
= !base::is_convertible
<T
*, base::subtle::RefCountedBase
*>::value
&&
173 !base::is_convertible
<T
*, base::subtle::RefCountedThreadSafeBase
*>::
178 template <typename T
>
179 struct ShouldAbortOnSelfReset
{
180 template <typename U
>
181 static NoType
Test(const typename
U::AllowSelfReset
*);
183 template <typename U
>
184 static YesType
Test(...);
186 static const bool value
= sizeof(Test
<T
>(0)) == sizeof(YesType
);
189 // Minimal implementation of the core logic of scoped_ptr, suitable for
190 // reuse in both scoped_ptr and its specializations.
191 template <class T
, class D
>
192 class scoped_ptr_impl
{
194 explicit scoped_ptr_impl(T
* p
) : data_(p
) {}
196 // Initializer for deleters that have data parameters.
197 scoped_ptr_impl(T
* p
, const D
& d
) : data_(p
, d
) {}
199 // Templated constructor that destructively takes the value from another
201 template <typename U
, typename V
>
202 scoped_ptr_impl(scoped_ptr_impl
<U
, V
>* other
)
203 : data_(other
->release(), other
->get_deleter()) {
204 // We do not support move-only deleters. We could modify our move
205 // emulation to have base::subtle::move() and base::subtle::forward()
206 // functions that are imperfect emulations of their C++11 equivalents,
207 // but until there's a requirement, just assume deleters are copyable.
210 template <typename U
, typename V
>
211 void TakeState(scoped_ptr_impl
<U
, V
>* other
) {
212 // See comment in templated constructor above regarding lack of support
213 // for move-only deleters.
214 reset(other
->release());
215 get_deleter() = other
->get_deleter();
219 if (data_
.ptr
!= nullptr) {
220 // Not using get_deleter() saves one function call in non-optimized
222 static_cast<D
&>(data_
)(data_
.ptr
);
227 // This is a self-reset, which is no longer allowed for default deleters:
228 // https://crbug.com/162971
229 assert(!ShouldAbortOnSelfReset
<D
>::value
|| p
== nullptr || p
!= data_
.ptr
);
231 // Note that running data_.ptr = p can lead to undefined behavior if
232 // get_deleter()(get()) deletes this. In order to prevent this, reset()
233 // should update the stored pointer before deleting its old value.
235 // However, changing reset() to use that behavior may cause current code to
236 // break in unexpected ways. If the destruction of the owned object
237 // dereferences the scoped_ptr when it is destroyed by a call to reset(),
238 // then it will incorrectly dispatch calls to |p| rather than the original
239 // value of |data_.ptr|.
241 // During the transition period, set the stored pointer to nullptr while
242 // deleting the object. Eventually, this safety check will be removed to
243 // prevent the scenario initially described from occuring and
244 // http://crbug.com/176091 can be closed.
248 static_cast<D
&>(data_
)(old
);
252 T
* get() const { return data_
.ptr
; }
254 D
& get_deleter() { return data_
; }
255 const D
& get_deleter() const { return data_
; }
257 void swap(scoped_ptr_impl
& p2
) {
258 // Standard swap idiom: 'using std::swap' ensures that std::swap is
259 // present in the overload set, but we call swap unqualified so that
260 // any more-specific overloads can be used, if available.
262 swap(static_cast<D
&>(data_
), static_cast<D
&>(p2
.data_
));
263 swap(data_
.ptr
, p2
.data_
.ptr
);
267 T
* old_ptr
= data_
.ptr
;
273 // Needed to allow type-converting constructor.
274 template <typename U
, typename V
> friend class scoped_ptr_impl
;
276 // Use the empty base class optimization to allow us to have a D
277 // member, while avoiding any space overhead for it when D is an
278 // empty class. See e.g. http://www.cantrip.org/emptyopt.html for a good
279 // discussion of this technique.
280 struct Data
: public D
{
281 explicit Data(T
* ptr_in
) : ptr(ptr_in
) {}
282 Data(T
* ptr_in
, const D
& other
) : D(other
), ptr(ptr_in
) {}
288 DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl
);
291 } // namespace internal
295 // A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
296 // automatically deletes the pointer it holds (if any).
297 // That is, scoped_ptr<T> owns the T object that it points to.
298 // Like a T*, a scoped_ptr<T> may hold either nullptr or a pointer to a T
299 // object. Also like T*, scoped_ptr<T> is thread-compatible, and once you
300 // dereference it, you get the thread safety guarantees of T.
302 // The size of scoped_ptr is small. On most compilers, when using the
303 // DefaultDeleter, sizeof(scoped_ptr<T>) == sizeof(T*). Custom deleters will
304 // increase the size proportional to whatever state they need to have. See
305 // comments inside scoped_ptr_impl<> for details.
307 // Current implementation targets having a strict subset of C++11's
308 // unique_ptr<> features. Known deficiencies include not supporting move-only
309 // deleteres, function pointers as deleters, and deleters with reference
311 template <class T
, class D
= base::DefaultDeleter
<T
> >
313 MOVE_ONLY_TYPE_WITH_MOVE_CONSTRUCTOR_FOR_CPP_03(scoped_ptr
)
315 COMPILE_ASSERT(base::internal::IsNotRefCounted
<T
>::value
,
316 T_is_refcounted_type_and_needs_scoped_refptr
);
319 // The element and deleter types.
320 typedef T element_type
;
321 typedef D deleter_type
;
323 // Constructor. Defaults to initializing with nullptr.
324 scoped_ptr() : impl_(nullptr) {}
326 // Constructor. Takes ownership of p.
327 explicit scoped_ptr(element_type
* p
) : impl_(p
) {}
329 // Constructor. Allows initialization of a stateful deleter.
330 scoped_ptr(element_type
* p
, const D
& d
) : impl_(p
, d
) {}
332 // Constructor. Allows construction from a nullptr.
333 scoped_ptr(decltype(nullptr)) : impl_(nullptr) {}
335 // Constructor. Allows construction from a scoped_ptr rvalue for a
336 // convertible type and deleter.
338 // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this constructor distinct
339 // from the normal move constructor. By C++11 20.7.1.2.1.21, this constructor
340 // has different post-conditions if D is a reference type. Since this
341 // implementation does not support deleters with reference type,
342 // we do not need a separate move constructor allowing us to avoid one
343 // use of SFINAE. You only need to care about this if you modify the
344 // implementation of scoped_ptr.
345 template <typename U
, typename V
>
346 scoped_ptr(scoped_ptr
<U
, V
>&& other
)
347 : impl_(&other
.impl_
) {
348 COMPILE_ASSERT(!base::is_array
<U
>::value
, U_cannot_be_an_array
);
351 // operator=. Allows assignment from a scoped_ptr rvalue for a convertible
354 // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this operator= distinct from
355 // the normal move assignment operator. By C++11 20.7.1.2.3.4, this templated
356 // form has different requirements on for move-only Deleters. Since this
357 // implementation does not support move-only Deleters, we do not need a
358 // separate move assignment operator allowing us to avoid one use of SFINAE.
359 // You only need to care about this if you modify the implementation of
361 template <typename U
, typename V
>
362 scoped_ptr
& operator=(scoped_ptr
<U
, V
>&& rhs
) {
363 COMPILE_ASSERT(!base::is_array
<U
>::value
, U_cannot_be_an_array
);
364 impl_
.TakeState(&rhs
.impl_
);
368 // operator=. Allows assignment from a nullptr. Deletes the currently owned
370 scoped_ptr
& operator=(decltype(nullptr)) {
375 // Reset. Deletes the currently owned object, if any.
376 // Then takes ownership of a new object, if given.
377 void reset(element_type
* p
= nullptr) { impl_
.reset(p
); }
379 // Accessors to get the owned object.
380 // operator* and operator-> will assert() if there is no current object.
381 element_type
& operator*() const {
382 assert(impl_
.get() != nullptr);
385 element_type
* operator->() const {
386 assert(impl_
.get() != nullptr);
389 element_type
* get() const { return impl_
.get(); }
391 // Access to the deleter.
392 deleter_type
& get_deleter() { return impl_
.get_deleter(); }
393 const deleter_type
& get_deleter() const { return impl_
.get_deleter(); }
395 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
396 // implicitly convertible to a real bool (which is dangerous).
398 // Note that this trick is only safe when the == and != operators
399 // are declared explicitly, as otherwise "scoped_ptr1 ==
400 // scoped_ptr2" will compile but do the wrong thing (i.e., convert
401 // to Testable and then do the comparison).
403 typedef base::internal::scoped_ptr_impl
<element_type
, deleter_type
>
404 scoped_ptr::*Testable
;
407 operator Testable() const {
408 return impl_
.get() ? &scoped_ptr::impl_
: nullptr;
411 // Comparison operators.
412 // These return whether two scoped_ptr refer to the same object, not just to
413 // two different but equal objects.
414 bool operator==(const element_type
* p
) const { return impl_
.get() == p
; }
415 bool operator!=(const element_type
* p
) const { return impl_
.get() != p
; }
417 // Swap two scoped pointers.
418 void swap(scoped_ptr
& p2
) {
419 impl_
.swap(p2
.impl_
);
422 // Release a pointer.
423 // The return value is the current pointer held by this object. If this object
424 // holds a nullptr, the return value is nullptr. After this operation, this
425 // object will hold a nullptr, and will not own the object any more.
426 element_type
* release() WARN_UNUSED_RESULT
{
427 return impl_
.release();
431 // Needed to reach into |impl_| in the constructor.
432 template <typename U
, typename V
> friend class scoped_ptr
;
433 base::internal::scoped_ptr_impl
<element_type
, deleter_type
> impl_
;
435 // Forbidden for API compatibility with std::unique_ptr.
436 explicit scoped_ptr(int disallow_construction_from_null
);
438 // Forbid comparison of scoped_ptr types. If U != T, it totally
439 // doesn't make sense, and if U == T, it still doesn't make sense
440 // because you should never have the same object owned by two different
442 template <class U
> bool operator==(scoped_ptr
<U
> const& p2
) const;
443 template <class U
> bool operator!=(scoped_ptr
<U
> const& p2
) const;
446 template <class T
, class D
>
447 class scoped_ptr
<T
[], D
> {
448 MOVE_ONLY_TYPE_WITH_MOVE_CONSTRUCTOR_FOR_CPP_03(scoped_ptr
)
451 // The element and deleter types.
452 typedef T element_type
;
453 typedef D deleter_type
;
455 // Constructor. Defaults to initializing with nullptr.
456 scoped_ptr() : impl_(nullptr) {}
458 // Constructor. Stores the given array. Note that the argument's type
459 // must exactly match T*. In particular:
460 // - it cannot be a pointer to a type derived from T, because it is
461 // inherently unsafe in the general case to access an array through a
462 // pointer whose dynamic type does not match its static type (eg., if
463 // T and the derived types had different sizes access would be
464 // incorrectly calculated). Deletion is also always undefined
465 // (C++98 [expr.delete]p3). If you're doing this, fix your code.
466 // - it cannot be const-qualified differently from T per unique_ptr spec
467 // (http://cplusplus.github.com/LWG/lwg-active.html#2118). Users wanting
468 // to work around this may use const_cast<const T*>().
469 explicit scoped_ptr(element_type
* array
) : impl_(array
) {}
471 // Constructor. Allows construction from a nullptr.
472 scoped_ptr(decltype(nullptr)) : impl_(nullptr) {}
474 // Constructor. Allows construction from a scoped_ptr rvalue.
475 scoped_ptr(scoped_ptr
&& other
) : impl_(&other
.impl_
) {}
477 // operator=. Allows assignment from a scoped_ptr rvalue.
478 scoped_ptr
& operator=(scoped_ptr
&& rhs
) {
479 impl_
.TakeState(&rhs
.impl_
);
483 // operator=. Allows assignment from a nullptr. Deletes the currently owned
485 scoped_ptr
& operator=(decltype(nullptr)) {
490 // Reset. Deletes the currently owned array, if any.
491 // Then takes ownership of a new object, if given.
492 void reset(element_type
* array
= nullptr) { impl_
.reset(array
); }
494 // Accessors to get the owned array.
495 element_type
& operator[](size_t i
) const {
496 assert(impl_
.get() != nullptr);
497 return impl_
.get()[i
];
499 element_type
* get() const { return impl_
.get(); }
501 // Access to the deleter.
502 deleter_type
& get_deleter() { return impl_
.get_deleter(); }
503 const deleter_type
& get_deleter() const { return impl_
.get_deleter(); }
505 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
506 // implicitly convertible to a real bool (which is dangerous).
508 typedef base::internal::scoped_ptr_impl
<element_type
, deleter_type
>
509 scoped_ptr::*Testable
;
512 operator Testable() const {
513 return impl_
.get() ? &scoped_ptr::impl_
: nullptr;
516 // Comparison operators.
517 // These return whether two scoped_ptr refer to the same object, not just to
518 // two different but equal objects.
519 bool operator==(element_type
* array
) const { return impl_
.get() == array
; }
520 bool operator!=(element_type
* array
) const { return impl_
.get() != array
; }
522 // Swap two scoped pointers.
523 void swap(scoped_ptr
& p2
) {
524 impl_
.swap(p2
.impl_
);
527 // Release a pointer.
528 // The return value is the current pointer held by this object. If this object
529 // holds a nullptr, the return value is nullptr. After this operation, this
530 // object will hold a nullptr, and will not own the object any more.
531 element_type
* release() WARN_UNUSED_RESULT
{
532 return impl_
.release();
536 // Force element_type to be a complete type.
537 enum { type_must_be_complete
= sizeof(element_type
) };
539 // Actually hold the data.
540 base::internal::scoped_ptr_impl
<element_type
, deleter_type
> impl_
;
542 // Disable initialization from any type other than element_type*, by
543 // providing a constructor that matches such an initialization, but is
544 // private and has no definition. This is disabled because it is not safe to
545 // call delete[] on an array whose static type does not match its dynamic
547 template <typename U
> explicit scoped_ptr(U
* array
);
548 explicit scoped_ptr(int disallow_construction_from_null
);
550 // Disable reset() from any type other than element_type*, for the same
551 // reasons as the constructor above.
552 template <typename U
> void reset(U
* array
);
553 void reset(int disallow_reset_from_null
);
555 // Forbid comparison of scoped_ptr types. If U != T, it totally
556 // doesn't make sense, and if U == T, it still doesn't make sense
557 // because you should never have the same object owned by two different
559 template <class U
> bool operator==(scoped_ptr
<U
> const& p2
) const;
560 template <class U
> bool operator!=(scoped_ptr
<U
> const& p2
) const;
564 template <class T
, class D
>
565 void swap(scoped_ptr
<T
, D
>& p1
, scoped_ptr
<T
, D
>& p2
) {
569 template <class T
, class D
>
570 bool operator==(T
* p1
, const scoped_ptr
<T
, D
>& p2
) {
571 return p1
== p2
.get();
574 template <class T
, class D
>
575 bool operator!=(T
* p1
, const scoped_ptr
<T
, D
>& p2
) {
576 return p1
!= p2
.get();
579 // A function to convert T* into scoped_ptr<T>
580 // Doing e.g. make_scoped_ptr(new FooBarBaz<type>(arg)) is a shorter notation
581 // for scoped_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
582 template <typename T
>
583 scoped_ptr
<T
> make_scoped_ptr(T
* ptr
) {
584 return scoped_ptr
<T
>(ptr
);
587 template <typename T
>
588 std::ostream
& operator<<(std::ostream
& out
, const scoped_ptr
<T
>& p
) {
589 return out
<< p
.get();
592 #endif // BASE_MEMORY_SCOPED_PTR_H_