2 * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
11 // Borrowed from Chromium's src/base/memory/scoped_ptr.h.
13 // Scopers help you manage ownership of a pointer, helping you easily manage the
14 // a pointer within a scope, and automatically destroying the pointer at the
15 // end of a scope. There are two main classes you will use, which correspond
16 // to the operators new/delete and new[]/delete[].
18 // Example usage (scoped_ptr<T>):
20 // scoped_ptr<Foo> foo(new Foo("wee"));
21 // } // foo goes out of scope, releasing the pointer with it.
24 // scoped_ptr<Foo> foo; // No pointer managed.
25 // foo.reset(new Foo("wee")); // Now a pointer is managed.
26 // foo.reset(new Foo("wee2")); // Foo("wee") was destroyed.
27 // foo.reset(new Foo("wee3")); // Foo("wee2") was destroyed.
28 // foo->Method(); // Foo::Method() called.
29 // foo.get()->Method(); // Foo::Method() called.
30 // SomeFunc(foo.release()); // SomeFunc takes ownership, foo no longer
31 // // manages a pointer.
32 // foo.reset(new Foo("wee4")); // foo manages a pointer again.
33 // foo.reset(); // Foo("wee4") destroyed, foo no longer
34 // // manages a pointer.
35 // } // foo wasn't managing a pointer, so nothing was destroyed.
37 // Example usage (scoped_ptr<T[]>):
39 // scoped_ptr<Foo[]> foo(new Foo[100]);
40 // foo.get()->Method(); // Foo::Method on the 0th element.
41 // foo[10].Method(); // Foo::Method on the 10th element.
44 // These scopers also implement part of the functionality of C++11 unique_ptr
45 // in that they are "movable but not copyable." You can use the scopers in
46 // the parameter and return types of functions to signify ownership transfer
47 // in to and out of a function. When calling a function that has a scoper
48 // as the argument type, it must be called with the result of an analogous
49 // scoper's Pass() function or another function that generates a temporary;
50 // passing by copy will NOT work. Here is an example using scoped_ptr:
52 // void TakesOwnership(scoped_ptr<Foo> arg) {
53 // // Do something with arg
55 // scoped_ptr<Foo> CreateFoo() {
56 // // No need for calling Pass() because we are constructing a temporary
57 // // for the return value.
58 // return scoped_ptr<Foo>(new Foo("new"));
60 // scoped_ptr<Foo> PassThru(scoped_ptr<Foo> arg) {
65 // scoped_ptr<Foo> ptr(new Foo("yay")); // ptr manages Foo("yay").
66 // TakesOwnership(ptr.Pass()); // ptr no longer owns Foo("yay").
67 // scoped_ptr<Foo> ptr2 = CreateFoo(); // ptr2 owns the return Foo.
68 // scoped_ptr<Foo> ptr3 = // ptr3 now owns what was in ptr2.
69 // PassThru(ptr2.Pass()); // ptr2 is correspondingly NULL.
72 // Notice that if you do not call Pass() when returning from PassThru(), or
73 // when invoking TakesOwnership(), the code will not compile because scopers
74 // are not copyable; they only implement move semantics which require calling
75 // the Pass() function to signify a destructive transfer of state. CreateFoo()
76 // is different though because we are constructing a temporary on the return
77 // line and thus can avoid needing to call Pass().
79 // Pass() properly handles upcast in initialization, i.e. you can use a
80 // scoped_ptr<Child> to initialize a scoped_ptr<Parent>:
82 // scoped_ptr<Foo> foo(new Foo());
83 // scoped_ptr<FooParent> parent(foo.Pass());
85 // PassAs<>() should be used to upcast return value in return statement:
87 // scoped_ptr<Foo> CreateFoo() {
88 // scoped_ptr<FooChild> result(new FooChild());
89 // return result.PassAs<Foo>();
92 // Note that PassAs<>() is implemented only for scoped_ptr<T>, but not for
93 // scoped_ptr<T[]>. This is because casting array pointers may not be safe.
95 #ifndef WEBRTC_SYSTEM_WRAPPERS_INTERFACE_SCOPED_PTR_H_
96 #define WEBRTC_SYSTEM_WRAPPERS_INTERFACE_SCOPED_PTR_H_
98 // This is an implementation designed to match the anticipated future TR2
99 // implementation of the scoped_ptr class.
105 #include <algorithm> // For std::swap().
107 #include "webrtc/system_wrappers/interface/compile_assert.h"
108 #include "webrtc/system_wrappers/interface/constructor_magic.h"
109 #include "webrtc/system_wrappers/interface/template_util.h"
110 #include "webrtc/system_wrappers/source/move.h"
111 #include "webrtc/typedefs.h"
115 // Function object which deletes its parameter, which must be a pointer.
116 // If C is an array type, invokes 'delete[]' on the parameter; otherwise,
117 // invokes 'delete'. The default deleter for scoped_ptr<T>.
119 struct DefaultDeleter {
121 template <typename U> DefaultDeleter(const DefaultDeleter<U>& other) {
122 // IMPLEMENTATION NOTE: C++11 20.7.1.1.2p2 only provides this constructor
123 // if U* is implicitly convertible to T* and U is not an array type.
125 // Correct implementation should use SFINAE to disable this
126 // constructor. However, since there are no other 1-argument constructors,
127 // using a COMPILE_ASSERT() based on is_convertible<> and requiring
128 // complete types is simpler and will cause compile failures for equivalent
131 // Note, the is_convertible<U*, T*> check also ensures that U is not an
132 // array. T is guaranteed to be a non-array, so any U* where U is an array
133 // cannot convert to T*.
134 enum { T_must_be_complete = sizeof(T) };
135 enum { U_must_be_complete = sizeof(U) };
136 COMPILE_ASSERT((webrtc::is_convertible<U*, T*>::value),
137 U_ptr_must_implicitly_convert_to_T_ptr);
139 inline void operator()(T* ptr) const {
140 enum { type_must_be_complete = sizeof(T) };
145 // Specialization of DefaultDeleter for array types.
147 struct DefaultDeleter<T[]> {
148 inline void operator()(T* ptr) const {
149 enum { type_must_be_complete = sizeof(T) };
154 // Disable this operator for any U != T because it is undefined to execute
155 // an array delete when the static type of the array mismatches the dynamic
159 // C++98 [expr.delete]p3
160 // http://cplusplus.github.com/LWG/lwg-defects.html#938
161 template <typename U> void operator()(U* array) const;
164 template <class T, int n>
165 struct DefaultDeleter<T[n]> {
166 // Never allow someone to declare something like scoped_ptr<int[10]>.
167 COMPILE_ASSERT(sizeof(T) == -1, do_not_use_array_with_size_as_type);
170 // Function object which invokes 'free' on its parameter, which must be
171 // a pointer. Can be used to store malloc-allocated pointers in scoped_ptr:
173 // scoped_ptr<int, webrtc::FreeDeleter> foo_ptr(
174 // static_cast<int*>(malloc(sizeof(int))));
176 inline void operator()(void* ptr) const {
183 // Minimal implementation of the core logic of scoped_ptr, suitable for
184 // reuse in both scoped_ptr and its specializations.
185 template <class T, class D>
186 class scoped_ptr_impl {
188 explicit scoped_ptr_impl(T* p) : data_(p) { }
190 // Initializer for deleters that have data parameters.
191 scoped_ptr_impl(T* p, const D& d) : data_(p, d) {}
193 // Templated constructor that destructively takes the value from another
195 template <typename U, typename V>
196 scoped_ptr_impl(scoped_ptr_impl<U, V>* other)
197 : data_(other->release(), other->get_deleter()) {
198 // We do not support move-only deleters. We could modify our move
199 // emulation to have webrtc::subtle::move() and webrtc::subtle::forward()
200 // functions that are imperfect emulations of their C++11 equivalents,
201 // but until there's a requirement, just assume deleters are copyable.
204 template <typename U, typename V>
205 void TakeState(scoped_ptr_impl<U, V>* other) {
206 // See comment in templated constructor above regarding lack of support
207 // for move-only deleters.
208 reset(other->release());
209 get_deleter() = other->get_deleter();
213 if (data_.ptr != NULL) {
214 // Not using get_deleter() saves one function call in non-optimized
216 static_cast<D&>(data_)(data_.ptr);
221 // This is a self-reset, which is no longer allowed: http://crbug.com/162971
222 if (p != NULL && p == data_.ptr)
225 // Note that running data_.ptr = p can lead to undefined behavior if
226 // get_deleter()(get()) deletes this. In order to pevent this, reset()
227 // should update the stored pointer before deleting its old value.
229 // However, changing reset() to use that behavior may cause current code to
230 // break in unexpected ways. If the destruction of the owned object
231 // dereferences the scoped_ptr when it is destroyed by a call to reset(),
232 // then it will incorrectly dispatch calls to |p| rather than the original
233 // value of |data_.ptr|.
235 // During the transition period, set the stored pointer to NULL while
236 // deleting the object. Eventually, this safety check will be removed to
237 // prevent the scenario initially described from occuring and
238 // http://crbug.com/176091 can be closed.
242 static_cast<D&>(data_)(old);
246 T* get() const { return data_.ptr; }
248 D& get_deleter() { return data_; }
249 const D& get_deleter() const { return data_; }
251 void swap(scoped_ptr_impl& p2) {
252 // Standard swap idiom: 'using std::swap' ensures that std::swap is
253 // present in the overload set, but we call swap unqualified so that
254 // any more-specific overloads can be used, if available.
256 swap(static_cast<D&>(data_), static_cast<D&>(p2.data_));
257 swap(data_.ptr, p2.data_.ptr);
261 T* old_ptr = data_.ptr;
267 // Needed to allow type-converting constructor.
268 template <typename U, typename V> friend class scoped_ptr_impl;
270 // Use the empty base class optimization to allow us to have a D
271 // member, while avoiding any space overhead for it when D is an
272 // empty class. See e.g. http://www.cantrip.org/emptyopt.html for a good
273 // discussion of this technique.
274 struct Data : public D {
275 explicit Data(T* ptr_in) : ptr(ptr_in) {}
276 Data(T* ptr_in, const D& other) : D(other), ptr(ptr_in) {}
282 DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl);
285 } // namespace internal
287 // A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
288 // automatically deletes the pointer it holds (if any).
289 // That is, scoped_ptr<T> owns the T object that it points to.
290 // Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object.
291 // Also like T*, scoped_ptr<T> is thread-compatible, and once you
292 // dereference it, you get the thread safety guarantees of T.
294 // The size of scoped_ptr is small. On most compilers, when using the
295 // DefaultDeleter, sizeof(scoped_ptr<T>) == sizeof(T*). Custom deleters will
296 // increase the size proportional to whatever state they need to have. See
297 // comments inside scoped_ptr_impl<> for details.
299 // Current implementation targets having a strict subset of C++11's
300 // unique_ptr<> features. Known deficiencies include not supporting move-only
301 // deleteres, function pointers as deleters, and deleters with reference
303 template <class T, class D = webrtc::DefaultDeleter<T> >
305 WEBRTC_MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue)
308 // The element and deleter types.
309 typedef T element_type;
310 typedef D deleter_type;
312 // Constructor. Defaults to initializing with NULL.
313 scoped_ptr() : impl_(NULL) { }
315 // Constructor. Takes ownership of p.
316 explicit scoped_ptr(element_type* p) : impl_(p) { }
318 // Constructor. Allows initialization of a stateful deleter.
319 scoped_ptr(element_type* p, const D& d) : impl_(p, d) { }
321 // Constructor. Allows construction from a scoped_ptr rvalue for a
322 // convertible type and deleter.
324 // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this constructor distinct
325 // from the normal move constructor. By C++11 20.7.1.2.1.21, this constructor
326 // has different post-conditions if D is a reference type. Since this
327 // implementation does not support deleters with reference type,
328 // we do not need a separate move constructor allowing us to avoid one
329 // use of SFINAE. You only need to care about this if you modify the
330 // implementation of scoped_ptr.
331 template <typename U, typename V>
332 scoped_ptr(scoped_ptr<U, V> other) : impl_(&other.impl_) {
333 COMPILE_ASSERT(!webrtc::is_array<U>::value, U_cannot_be_an_array);
336 // Constructor. Move constructor for C++03 move emulation of this type.
337 scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { }
339 // operator=. Allows assignment from a scoped_ptr rvalue for a convertible
342 // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this operator= distinct from
343 // the normal move assignment operator. By C++11 20.7.1.2.3.4, this templated
344 // form has different requirements on for move-only Deleters. Since this
345 // implementation does not support move-only Deleters, we do not need a
346 // separate move assignment operator allowing us to avoid one use of SFINAE.
347 // You only need to care about this if you modify the implementation of
349 template <typename U, typename V>
350 scoped_ptr& operator=(scoped_ptr<U, V> rhs) {
351 COMPILE_ASSERT(!webrtc::is_array<U>::value, U_cannot_be_an_array);
352 impl_.TakeState(&rhs.impl_);
356 // Reset. Deletes the currently owned object, if any.
357 // Then takes ownership of a new object, if given.
358 void reset(element_type* p = NULL) { impl_.reset(p); }
360 // Accessors to get the owned object.
361 // operator* and operator-> will assert() if there is no current object.
362 element_type& operator*() const {
363 assert(impl_.get() != NULL);
366 element_type* operator->() const {
367 assert(impl_.get() != NULL);
370 element_type* get() const { return impl_.get(); }
372 // Access to the deleter.
373 deleter_type& get_deleter() { return impl_.get_deleter(); }
374 const deleter_type& get_deleter() const { return impl_.get_deleter(); }
376 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
377 // implicitly convertible to a real bool (which is dangerous).
379 // Note that this trick is only safe when the == and != operators
380 // are declared explicitly, as otherwise "scoped_ptr1 ==
381 // scoped_ptr2" will compile but do the wrong thing (i.e., convert
382 // to Testable and then do the comparison).
384 typedef webrtc::internal::scoped_ptr_impl<element_type, deleter_type>
385 scoped_ptr::*Testable;
388 operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; }
390 // Comparison operators.
391 // These return whether two scoped_ptr refer to the same object, not just to
392 // two different but equal objects.
393 bool operator==(const element_type* p) const { return impl_.get() == p; }
394 bool operator!=(const element_type* p) const { return impl_.get() != p; }
396 // Swap two scoped pointers.
397 void swap(scoped_ptr& p2) {
398 impl_.swap(p2.impl_);
401 // Release a pointer.
402 // The return value is the current pointer held by this object.
403 // If this object holds a NULL pointer, the return value is NULL.
404 // After this operation, this object will hold a NULL pointer,
405 // and will not own the object any more.
406 element_type* release() WARN_UNUSED_RESULT {
407 return impl_.release();
410 // C++98 doesn't support functions templates with default parameters which
411 // makes it hard to write a PassAs() that understands converting the deleter
412 // while preserving simple calling semantics.
414 // Until there is a use case for PassAs() with custom deleters, just ignore
415 // the custom deleter.
416 template <typename PassAsType>
417 scoped_ptr<PassAsType> PassAs() {
418 return scoped_ptr<PassAsType>(Pass());
422 // Needed to reach into |impl_| in the constructor.
423 template <typename U, typename V> friend class scoped_ptr;
424 webrtc::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
426 // Forbidden for API compatibility with std::unique_ptr.
427 explicit scoped_ptr(int disallow_construction_from_null);
429 // Forbid comparison of scoped_ptr types. If U != T, it totally
430 // doesn't make sense, and if U == T, it still doesn't make sense
431 // because you should never have the same object owned by two different
433 template <class U> bool operator==(scoped_ptr<U> const& p2) const;
434 template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
437 template <class T, class D>
438 class scoped_ptr<T[], D> {
439 WEBRTC_MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue)
442 // The element and deleter types.
443 typedef T element_type;
444 typedef D deleter_type;
446 // Constructor. Defaults to initializing with NULL.
447 scoped_ptr() : impl_(NULL) { }
449 // Constructor. Stores the given array. Note that the argument's type
450 // must exactly match T*. In particular:
451 // - it cannot be a pointer to a type derived from T, because it is
452 // inherently unsafe in the general case to access an array through a
453 // pointer whose dynamic type does not match its static type (eg., if
454 // T and the derived types had different sizes access would be
455 // incorrectly calculated). Deletion is also always undefined
456 // (C++98 [expr.delete]p3). If you're doing this, fix your code.
457 // - it cannot be NULL, because NULL is an integral expression, not a
458 // pointer to T. Use the no-argument version instead of explicitly
460 // - it cannot be const-qualified differently from T per unique_ptr spec
461 // (http://cplusplus.github.com/LWG/lwg-active.html#2118). Users wanting
462 // to work around this may use implicit_cast<const T*>().
463 // However, because of the first bullet in this comment, users MUST
464 // NOT use implicit_cast<Base*>() to upcast the static type of the array.
465 explicit scoped_ptr(element_type* array) : impl_(array) { }
467 // Constructor. Move constructor for C++03 move emulation of this type.
468 scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { }
470 // operator=. Move operator= for C++03 move emulation of this type.
471 scoped_ptr& operator=(RValue rhs) {
472 impl_.TakeState(&rhs.object->impl_);
476 // Reset. Deletes the currently owned array, if any.
477 // Then takes ownership of a new object, if given.
478 void reset(element_type* array = NULL) { impl_.reset(array); }
480 // Accessors to get the owned array.
481 element_type& operator[](size_t i) const {
482 assert(impl_.get() != NULL);
483 return impl_.get()[i];
485 element_type* get() const { return impl_.get(); }
487 // Access to the deleter.
488 deleter_type& get_deleter() { return impl_.get_deleter(); }
489 const deleter_type& get_deleter() const { return impl_.get_deleter(); }
491 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
492 // implicitly convertible to a real bool (which is dangerous).
494 typedef webrtc::internal::scoped_ptr_impl<element_type, deleter_type>
495 scoped_ptr::*Testable;
498 operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; }
500 // Comparison operators.
501 // These return whether two scoped_ptr refer to the same object, not just to
502 // two different but equal objects.
503 bool operator==(element_type* array) const { return impl_.get() == array; }
504 bool operator!=(element_type* array) const { return impl_.get() != array; }
506 // Swap two scoped pointers.
507 void swap(scoped_ptr& p2) {
508 impl_.swap(p2.impl_);
511 // Release a pointer.
512 // The return value is the current pointer held by this object.
513 // If this object holds a NULL pointer, the return value is NULL.
514 // After this operation, this object will hold a NULL pointer,
515 // and will not own the object any more.
516 element_type* release() WARN_UNUSED_RESULT {
517 return impl_.release();
521 // Force element_type to be a complete type.
522 enum { type_must_be_complete = sizeof(element_type) };
524 // Actually hold the data.
525 webrtc::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
527 // Disable initialization from any type other than element_type*, by
528 // providing a constructor that matches such an initialization, but is
529 // private and has no definition. This is disabled because it is not safe to
530 // call delete[] on an array whose static type does not match its dynamic
532 template <typename U> explicit scoped_ptr(U* array);
533 explicit scoped_ptr(int disallow_construction_from_null);
535 // Disable reset() from any type other than element_type*, for the same
536 // reasons as the constructor above.
537 template <typename U> void reset(U* array);
538 void reset(int disallow_reset_from_null);
540 // Forbid comparison of scoped_ptr types. If U != T, it totally
541 // doesn't make sense, and if U == T, it still doesn't make sense
542 // because you should never have the same object owned by two different
544 template <class U> bool operator==(scoped_ptr<U> const& p2) const;
545 template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
548 } // namespace webrtc
551 template <class T, class D>
552 void swap(webrtc::scoped_ptr<T, D>& p1, webrtc::scoped_ptr<T, D>& p2) {
556 template <class T, class D>
557 bool operator==(T* p1, const webrtc::scoped_ptr<T, D>& p2) {
558 return p1 == p2.get();
561 template <class T, class D>
562 bool operator!=(T* p1, const webrtc::scoped_ptr<T, D>& p2) {
563 return p1 != p2.get();
566 #endif // WEBRTC_SYSTEM_WRAPPERS_INTERFACE_SCOPED_PTR_H_