Update .DEPS.git
[chromium-blink-merge.git] / base / memory / scoped_ptr.h
blob3547b7a15397f9c58f3c5193401d6d9defae333d
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[].
9 //
10 // Example usage (scoped_ptr):
11 // {
12 // scoped_ptr<Foo> foo(new Foo("wee"));
13 // } // foo goes out of scope, releasing the pointer with it.
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.
29 // Example usage (scoped_array):
30 // {
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.
34 // }
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
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 // }
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 NULL.
62 // }
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>();
82 // }
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.
94 #include <assert.h>
95 #include <stddef.h>
96 #include <stdlib.h>
98 #include "base/basictypes.h"
99 #include "base/compiler_specific.h"
100 #include "base/move.h"
101 #include "base/template_util.h"
103 namespace base {
105 namespace subtle {
106 class RefCountedBase;
107 class RefCountedThreadSafeBase;
108 } // namespace subtle
110 namespace internal {
112 template <typename T> struct IsNotRefCounted {
113 enum {
114 value = !base::is_convertible<T*, base::subtle::RefCountedBase*>::value &&
115 !base::is_convertible<T*, base::subtle::RefCountedThreadSafeBase*>::
116 value
120 } // namespace internal
121 } // namespace base
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*)
132 template <class C>
133 class scoped_ptr {
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);
139 public:
141 // The element type
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
150 // convertible type.
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.
161 ~scoped_ptr() {
162 enum { type_must_be_complete = sizeof(C) };
163 delete ptr_;
166 // operator=. Allows assignment from a scoped_ptr rvalue for a convertible
167 // type.
168 template <typename U>
169 scoped_ptr& operator=(scoped_ptr<U> rhs) {
170 reset(rhs.release());
171 return *this;
174 // operator=. Move operator= for C++03 move emulation of this type.
175 scoped_ptr& operator=(RValue rhs) {
176 swap(*rhs->object);
177 return *this;
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) {
184 if (p != ptr_) {
185 enum { type_must_be_complete = sizeof(C) };
186 delete ptr_;
187 ptr_ = p;
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);
195 return *ptr_;
197 C* operator->() const {
198 assert(ptr_ != NULL);
199 return ptr_;
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) {
216 C* tmp = ptr_;
217 ptr_ = p2.ptr_;
218 p2.ptr_ = tmp;
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 {
227 C* retVal = ptr_;
228 ptr_ = NULL;
229 return retVal;
232 template <typename PassAsType>
233 scoped_ptr<PassAsType> PassAs() {
234 return scoped_ptr<PassAsType>(release());
237 private:
238 C* ptr_;
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;
248 // Free functions
249 template <class C>
250 void swap(scoped_ptr<C>& p1, scoped_ptr<C>& p2) {
251 p1.swap(p2);
254 template <class C>
255 bool operator==(C* p1, const scoped_ptr<C>& p2) {
256 return p1 == p2.get();
259 template <class C>
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*)
273 template <class C>
274 class scoped_array {
275 MOVE_ONLY_TYPE_FOR_CPP_03(scoped_array, RValue)
277 public:
279 // The element type
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.
294 ~scoped_array() {
295 enum { type_must_be_complete = sizeof(C) };
296 delete[] array_;
299 // operator=. Move operator= for C++03 move emulation of this type.
300 scoped_array& operator=(RValue rhs) {
301 swap(*rhs.object);
302 return *this;
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) {
309 if (p != array_) {
310 enum { type_must_be_complete = sizeof(C) };
311 delete[] array_;
312 array_ = p;
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 {
319 assert(i >= 0);
320 assert(array_ != NULL);
321 return array_[i];
324 // Get a pointer to the zeroth element of the current object.
325 // If there is no current object, return NULL.
326 C* get() const {
327 return array_;
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) {
343 C* tmp = array_;
344 array_ = p2.array_;
345 p2.array_ = tmp;
348 // Release an array.
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 {
354 C* retVal = array_;
355 array_ = NULL;
356 return retVal;
359 private:
360 C* array_;
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;
367 // Free functions
368 template <class C>
369 void swap(scoped_array<C>& p1, scoped_array<C>& p2) {
370 p1.swap(p2);
373 template <class C>
374 bool operator==(C* p1, const scoped_array<C>& p2) {
375 return p1 == p2.get();
378 template <class C>
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 {
386 public:
387 inline void operator()(void* x) const {
388 free(x);
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)
399 public:
401 // The element type
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
408 // realloc.
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() {
418 reset();
421 // operator=. Move operator= for C++03 move emulation of this type.
422 scoped_ptr_malloc& operator=(RValue rhs) {
423 swap(*rhs.object);
424 return *this;
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) {
431 if (ptr_ != p) {
432 FreeProc free_proc;
433 free_proc(ptr_);
434 ptr_ = p;
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);
443 return *ptr_;
446 C* operator->() const {
447 assert(ptr_ != NULL);
448 return ptr_;
451 C* get() const {
452 return ptr_;
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 {
466 return ptr_ == p;
469 bool operator!=(C* p) const {
470 return ptr_ != p;
473 // Swap two scoped pointers.
474 void swap(scoped_ptr_malloc & b) {
475 C* tmp = b.ptr_;
476 b.ptr_ = ptr_;
477 ptr_ = tmp;
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 {
486 C* tmp = ptr_;
487 ptr_ = NULL;
488 return tmp;
491 private:
492 C* ptr_;
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) {
503 a.swap(b);
506 template<class C, class FP> inline
507 bool operator==(C* p, const scoped_ptr_malloc<C, FP>& b) {
508 return p == b.get();
511 template<class C, class FP> inline
512 bool operator!=(C* p, const scoped_ptr_malloc<C, FP>& b) {
513 return p != b.get();
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_