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 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):
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_array):
31 // scoped_array<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 assignment, i.e. you can assign
72 // scoped_ptr<Child> to 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, but not for
85 // scoped_array. This is because casting array pointers may not be safe.
87 #ifndef BASE_MEMORY_SCOPED_PTR_H_
88 #define BASE_MEMORY_SCOPED_PTR_H_
90 // This is an implementation designed to match the anticipated future TR2
91 // implementation of the scoped_ptr class, and its closely-related brethren,
92 // scoped_array, scoped_ptr_malloc.
98 #include "base/basictypes.h"
99 #include "base/compiler_specific.h"
100 #include "base/move.h"
101 #include "base/template_util.h"
106 class RefCountedBase
;
107 class RefCountedThreadSafeBase
;
108 } // namespace subtle
112 template <typename T
> struct IsNotRefCounted
{
114 value
= !base::is_convertible
<T
*, base::subtle::RefCountedBase
*>::value
&&
115 !base::is_convertible
<T
*, base::subtle::RefCountedThreadSafeBase
*>::
120 } // namespace internal
123 // A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
124 // automatically deletes the pointer it holds (if any).
125 // That is, scoped_ptr<T> owns the T object that it points to.
126 // Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object.
127 // Also like T*, scoped_ptr<T> is thread-compatible, and once you
128 // dereference it, you get the thread safety guarantees of T.
130 // The size of a scoped_ptr is small:
131 // sizeof(scoped_ptr<C>) == sizeof(C*)
134 MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr
, RValue
)
136 COMPILE_ASSERT(base::internal::IsNotRefCounted
<C
>::value
,
137 C_is_refcounted_type_and_needs_scoped_refptr
);
142 typedef C element_type
;
144 // Constructor. Defaults to initializing with NULL.
145 // There is no way to create an uninitialized scoped_ptr.
146 // The input parameter must be allocated with new.
147 explicit scoped_ptr(C
* p
= NULL
) : ptr_(p
) { }
149 // Constructor. Allows construction from a scoped_ptr rvalue for a
151 template <typename U
>
152 scoped_ptr(scoped_ptr
<U
> other
) : ptr_(other
.release()) { }
154 // Constructor. Move constructor for C++03 move emulation of this type.
155 scoped_ptr(RValue rvalue
)
156 : ptr_(rvalue
.object
->release()) {
159 // Destructor. If there is a C object, delete it.
160 // We don't need to test ptr_ == NULL because C++ does that for us.
162 enum { type_must_be_complete
= sizeof(C
) };
166 // operator=. Allows assignment from a scoped_ptr rvalue for a convertible
168 template <typename U
>
169 scoped_ptr
& operator=(scoped_ptr
<U
> rhs
) {
170 reset(rhs
.release());
174 // operator=. Move operator= for C++03 move emulation of this type.
175 scoped_ptr
& operator=(RValue rhs
) {
180 // Reset. Deletes the current owned object, if any.
181 // Then takes ownership of a new object, if given.
182 // this->reset(this->get()) works.
183 void reset(C
* p
= NULL
) {
185 enum { type_must_be_complete
= sizeof(C
) };
191 // Accessors to get the owned object.
192 // operator* and operator-> will assert() if there is no current object.
193 C
& operator*() const {
194 assert(ptr_
!= NULL
);
197 C
* operator->() const {
198 assert(ptr_
!= NULL
);
201 C
* get() const { return ptr_
; }
203 // Allow scoped_ptr<C> to be used in boolean expressions, but not
204 // implicitly convertible to a real bool (which is dangerous).
205 typedef C
* scoped_ptr::*Testable
;
206 operator Testable() const { return ptr_
? &scoped_ptr::ptr_
: NULL
; }
208 // Comparison operators.
209 // These return whether two scoped_ptr refer to the same object, not just to
210 // two different but equal objects.
211 bool operator==(C
* p
) const { return ptr_
== p
; }
212 bool operator!=(C
* p
) const { return ptr_
!= p
; }
214 // Swap two scoped pointers.
215 void swap(scoped_ptr
& p2
) {
221 // Release a pointer.
222 // The return value is the current pointer held by this object.
223 // If this object holds a NULL pointer, the return value is NULL.
224 // After this operation, this object will hold a NULL pointer,
225 // and will not own the object any more.
226 C
* release() WARN_UNUSED_RESULT
{
232 template <typename PassAsType
>
233 scoped_ptr
<PassAsType
> PassAs() {
234 return scoped_ptr
<PassAsType
>(release());
240 // Forbid comparison of scoped_ptr types. If C2 != C, it totally doesn't
241 // make sense, and if C2 == C, it still doesn't make sense because you should
242 // never have the same object owned by two different scoped_ptrs.
243 template <class C2
> bool operator==(scoped_ptr
<C2
> const& p2
) const;
244 template <class C2
> bool operator!=(scoped_ptr
<C2
> const& p2
) const;
250 void swap(scoped_ptr
<C
>& p1
, scoped_ptr
<C
>& p2
) {
255 bool operator==(C
* p1
, const scoped_ptr
<C
>& p2
) {
256 return p1
== p2
.get();
260 bool operator!=(C
* p1
, const scoped_ptr
<C
>& p2
) {
261 return p1
!= p2
.get();
264 // scoped_array<C> is like scoped_ptr<C>, except that the caller must allocate
265 // with new [] and the destructor deletes objects with delete [].
267 // As with scoped_ptr<C>, a scoped_array<C> either points to an object
268 // or is NULL. A scoped_array<C> owns the object that it points to.
269 // scoped_array<T> is thread-compatible, and once you index into it,
270 // the returned objects have only the thread safety guarantees of T.
272 // Size: sizeof(scoped_array<C>) == sizeof(C*)
275 MOVE_ONLY_TYPE_FOR_CPP_03(scoped_array
, RValue
)
280 typedef C element_type
;
282 // Constructor. Defaults to initializing with NULL.
283 // There is no way to create an uninitialized scoped_array.
284 // The input parameter must be allocated with new [].
285 explicit scoped_array(C
* p
= NULL
) : array_(p
) { }
287 // Constructor. Move constructor for C++03 move emulation of this type.
288 scoped_array(RValue rvalue
)
289 : array_(rvalue
.object
->release()) {
292 // Destructor. If there is a C object, delete it.
293 // We don't need to test ptr_ == NULL because C++ does that for us.
295 enum { type_must_be_complete
= sizeof(C
) };
299 // operator=. Move operator= for C++03 move emulation of this type.
300 scoped_array
& operator=(RValue rhs
) {
305 // Reset. Deletes the current owned object, if any.
306 // Then takes ownership of a new object, if given.
307 // this->reset(this->get()) works.
308 void reset(C
* p
= NULL
) {
310 enum { type_must_be_complete
= sizeof(C
) };
316 // Get one element of the current object.
317 // Will assert() if there is no current object, or index i is negative.
318 C
& operator[](ptrdiff_t i
) const {
320 assert(array_
!= NULL
);
324 // Get a pointer to the zeroth element of the current object.
325 // If there is no current object, return NULL.
330 // Allow scoped_array<C> to be used in boolean expressions, but not
331 // implicitly convertible to a real bool (which is dangerous).
332 typedef C
* scoped_array::*Testable
;
333 operator Testable() const { return array_
? &scoped_array::array_
: NULL
; }
335 // Comparison operators.
336 // These return whether two scoped_array refer to the same object, not just to
337 // two different but equal objects.
338 bool operator==(C
* p
) const { return array_
== p
; }
339 bool operator!=(C
* p
) const { return array_
!= p
; }
341 // Swap two scoped arrays.
342 void swap(scoped_array
& p2
) {
349 // The return value is the current pointer held by this object.
350 // If this object holds a NULL pointer, the return value is NULL.
351 // After this operation, this object will hold a NULL pointer,
352 // and will not own the object any more.
353 C
* release() WARN_UNUSED_RESULT
{
362 // Forbid comparison of different scoped_array types.
363 template <class C2
> bool operator==(scoped_array
<C2
> const& p2
) const;
364 template <class C2
> bool operator!=(scoped_array
<C2
> const& p2
) const;
369 void swap(scoped_array
<C
>& p1
, scoped_array
<C
>& p2
) {
374 bool operator==(C
* p1
, const scoped_array
<C
>& p2
) {
375 return p1
== p2
.get();
379 bool operator!=(C
* p1
, const scoped_array
<C
>& p2
) {
380 return p1
!= p2
.get();
383 // This class wraps the c library function free() in a class that can be
384 // passed as a template argument to scoped_ptr_malloc below.
385 class ScopedPtrMallocFree
{
387 inline void operator()(void* x
) const {
392 // scoped_ptr_malloc<> is similar to scoped_ptr<>, but it accepts a
393 // second template argument, the functor used to free the object.
395 template<class C
, class FreeProc
= ScopedPtrMallocFree
>
396 class scoped_ptr_malloc
{
397 MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr_malloc
, RValue
)
402 typedef C element_type
;
404 // Constructor. Defaults to initializing with NULL.
405 // There is no way to create an uninitialized scoped_ptr.
406 // The input parameter must be allocated with an allocator that matches the
407 // Free functor. For the default Free functor, this is malloc, calloc, or
409 explicit scoped_ptr_malloc(C
* p
= NULL
): ptr_(p
) {}
411 // Constructor. Move constructor for C++03 move emulation of this type.
412 scoped_ptr_malloc(RValue rvalue
)
413 : ptr_(rvalue
.object
->release()) {
416 // Destructor. If there is a C object, call the Free functor.
417 ~scoped_ptr_malloc() {
421 // operator=. Move operator= for C++03 move emulation of this type.
422 scoped_ptr_malloc
& operator=(RValue rhs
) {
427 // Reset. Calls the Free functor on the current owned object, if any.
428 // Then takes ownership of a new object, if given.
429 // this->reset(this->get()) works.
430 void reset(C
* p
= NULL
) {
438 // Get the current object.
439 // operator* and operator-> will cause an assert() failure if there is
440 // no current object.
441 C
& operator*() const {
442 assert(ptr_
!= NULL
);
446 C
* operator->() const {
447 assert(ptr_
!= NULL
);
455 // Allow scoped_ptr_malloc<C> to be used in boolean expressions, but not
456 // implicitly convertible to a real bool (which is dangerous).
457 typedef C
* scoped_ptr_malloc::*Testable
;
458 operator Testable() const { return ptr_
? &scoped_ptr_malloc::ptr_
: NULL
; }
460 // Comparison operators.
461 // These return whether a scoped_ptr_malloc and a plain pointer refer
462 // to the same object, not just to two different but equal objects.
463 // For compatibility with the boost-derived implementation, these
464 // take non-const arguments.
465 bool operator==(C
* p
) const {
469 bool operator!=(C
* p
) const {
473 // Swap two scoped pointers.
474 void swap(scoped_ptr_malloc
& b
) {
480 // Release a pointer.
481 // The return value is the current pointer held by this object.
482 // If this object holds a NULL pointer, the return value is NULL.
483 // After this operation, this object will hold a NULL pointer,
484 // and will not own the object any more.
485 C
* release() WARN_UNUSED_RESULT
{
494 // no reason to use these: each scoped_ptr_malloc should have its own object
495 template <class C2
, class GP
>
496 bool operator==(scoped_ptr_malloc
<C2
, GP
> const& p
) const;
497 template <class C2
, class GP
>
498 bool operator!=(scoped_ptr_malloc
<C2
, GP
> const& p
) const;
501 template<class C
, class FP
> inline
502 void swap(scoped_ptr_malloc
<C
, FP
>& a
, scoped_ptr_malloc
<C
, FP
>& b
) {
506 template<class C
, class FP
> inline
507 bool operator==(C
* p
, const scoped_ptr_malloc
<C
, FP
>& b
) {
511 template<class C
, class FP
> inline
512 bool operator!=(C
* p
, const scoped_ptr_malloc
<C
, FP
>& b
) {
516 // A function to convert T* into scoped_ptr<T>
517 // Doing e.g. make_scoped_ptr(new FooBarBaz<type>(arg)) is a shorter notation
518 // for scoped_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
519 template <typename T
>
520 scoped_ptr
<T
> make_scoped_ptr(T
* ptr
) {
521 return scoped_ptr
<T
>(ptr
);
524 #endif // BASE_MEMORY_SCOPED_PTR_H_