blob: 0c0a637a2e7d88102e2b504f0f0739c027ce095f [file] [log] [blame]
henrike@webrtc.orgf7795df2014-05-13 18:00:26 +00001/*
2 * Copyright 2012 The WebRTC Project Authors. All rights reserved.
3 *
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.
9 */
10
11// Scopers help you manage ownership of a pointer, helping you easily manage the
12// a pointer within a scope, and automatically destroying the pointer at the
13// end of a scope. There are two main classes you will use, which correspond
14// to the operators new/delete and new[]/delete[].
15//
16// Example usage (scoped_ptr<T>):
17// {
18// scoped_ptr<Foo> foo(new Foo("wee"));
19// } // foo goes out of scope, releasing the pointer with it.
20//
21// {
22// scoped_ptr<Foo> foo; // No pointer managed.
23// foo.reset(new Foo("wee")); // Now a pointer is managed.
24// foo.reset(new Foo("wee2")); // Foo("wee") was destroyed.
25// foo.reset(new Foo("wee3")); // Foo("wee2") was destroyed.
26// foo->Method(); // Foo::Method() called.
27// foo.get()->Method(); // Foo::Method() called.
28// SomeFunc(foo.release()); // SomeFunc takes ownership, foo no longer
29// // manages a pointer.
30// foo.reset(new Foo("wee4")); // foo manages a pointer again.
31// foo.reset(); // Foo("wee4") destroyed, foo no longer
32// // manages a pointer.
33// } // foo wasn't managing a pointer, so nothing was destroyed.
34//
35// Example usage (scoped_ptr<T[]>):
36// {
37// scoped_ptr<Foo[]> foo(new Foo[100]);
38// foo.get()->Method(); // Foo::Method on the 0th element.
39// foo[10].Method(); // Foo::Method on the 10th element.
40// }
41//
42// These scopers also implement part of the functionality of C++11 unique_ptr
43// in that they are "movable but not copyable." You can use the scopers in
44// the parameter and return types of functions to signify ownership transfer
45// in to and out of a function. When calling a function that has a scoper
46// as the argument type, it must be called with the result of an analogous
47// scoper's Pass() function or another function that generates a temporary;
48// passing by copy will NOT work. Here is an example using scoped_ptr:
49//
50// void TakesOwnership(scoped_ptr<Foo> arg) {
51// // Do something with arg
52// }
53// scoped_ptr<Foo> CreateFoo() {
54// // No need for calling Pass() because we are constructing a temporary
55// // for the return value.
56// return scoped_ptr<Foo>(new Foo("new"));
57// }
58// scoped_ptr<Foo> PassThru(scoped_ptr<Foo> arg) {
59// return arg.Pass();
60// }
61//
62// {
63// scoped_ptr<Foo> ptr(new Foo("yay")); // ptr manages Foo("yay").
64// TakesOwnership(ptr.Pass()); // ptr no longer owns Foo("yay").
65// scoped_ptr<Foo> ptr2 = CreateFoo(); // ptr2 owns the return Foo.
66// scoped_ptr<Foo> ptr3 = // ptr3 now owns what was in ptr2.
67// PassThru(ptr2.Pass()); // ptr2 is correspondingly NULL.
68// }
69//
70// Notice that if you do not call Pass() when returning from PassThru(), or
71// when invoking TakesOwnership(), the code will not compile because scopers
72// are not copyable; they only implement move semantics which require calling
73// the Pass() function to signify a destructive transfer of state. CreateFoo()
74// is different though because we are constructing a temporary on the return
75// line and thus can avoid needing to call Pass().
76//
77// Pass() properly handles upcast in initialization, i.e. you can use a
78// scoped_ptr<Child> to initialize a scoped_ptr<Parent>:
79//
80// scoped_ptr<Foo> foo(new Foo());
81// scoped_ptr<FooParent> parent(foo.Pass());
82//
83// PassAs<>() should be used to upcast return value in return statement:
84//
85// scoped_ptr<Foo> CreateFoo() {
86// scoped_ptr<FooChild> result(new FooChild());
87// return result.PassAs<Foo>();
88// }
89//
90// Note that PassAs<>() is implemented only for scoped_ptr<T>, but not for
91// scoped_ptr<T[]>. This is because casting array pointers may not be safe.
92
93#ifndef WEBRTC_BASE_SCOPED_PTR_H__
94#define WEBRTC_BASE_SCOPED_PTR_H__
95
96#include <stddef.h> // for ptrdiff_t
97#include <stdlib.h> // for free() decl
98
99#include <algorithm> // For std::swap().
100
101#include "webrtc/base/common.h" // for ASSERT
102#include "webrtc/base/compile_assert.h" // for COMPILE_ASSERT
103#include "webrtc/base/move.h" // for TALK_MOVE_ONLY_TYPE_FOR_CPP_03
104#include "webrtc/base/template_util.h" // for is_convertible, is_array
105
106#ifdef WEBRTC_WIN
107namespace std { using ::ptrdiff_t; };
108#endif // WEBRTC_WIN
109
110namespace rtc {
111
112// Function object which deletes its parameter, which must be a pointer.
113// If C is an array type, invokes 'delete[]' on the parameter; otherwise,
114// invokes 'delete'. The default deleter for scoped_ptr<T>.
115template <class T>
116struct DefaultDeleter {
117 DefaultDeleter() {}
118 template <typename U> DefaultDeleter(const DefaultDeleter<U>& other) {
119 // IMPLEMENTATION NOTE: C++11 20.7.1.1.2p2 only provides this constructor
120 // if U* is implicitly convertible to T* and U is not an array type.
121 //
122 // Correct implementation should use SFINAE to disable this
123 // constructor. However, since there are no other 1-argument constructors,
124 // using a COMPILE_ASSERT() based on is_convertible<> and requiring
125 // complete types is simpler and will cause compile failures for equivalent
126 // misuses.
127 //
128 // Note, the is_convertible<U*, T*> check also ensures that U is not an
129 // array. T is guaranteed to be a non-array, so any U* where U is an array
130 // cannot convert to T*.
131 enum { T_must_be_complete = sizeof(T) };
132 enum { U_must_be_complete = sizeof(U) };
133 COMPILE_ASSERT((rtc::is_convertible<U*, T*>::value),
134 U_ptr_must_implicitly_convert_to_T_ptr);
135 }
136 inline void operator()(T* ptr) const {
137 enum { type_must_be_complete = sizeof(T) };
138 delete ptr;
139 }
140};
141
142// Specialization of DefaultDeleter for array types.
143template <class T>
144struct DefaultDeleter<T[]> {
145 inline void operator()(T* ptr) const {
146 enum { type_must_be_complete = sizeof(T) };
147 delete[] ptr;
148 }
149
150 private:
151 // Disable this operator for any U != T because it is undefined to execute
152 // an array delete when the static type of the array mismatches the dynamic
153 // type.
154 //
155 // References:
156 // C++98 [expr.delete]p3
157 // http://cplusplus.github.com/LWG/lwg-defects.html#938
158 template <typename U> void operator()(U* array) const;
159};
160
161template <class T, int n>
162struct DefaultDeleter<T[n]> {
163 // Never allow someone to declare something like scoped_ptr<int[10]>.
164 COMPILE_ASSERT(sizeof(T) == -1, do_not_use_array_with_size_as_type);
165};
166
167// Function object which invokes 'free' on its parameter, which must be
168// a pointer. Can be used to store malloc-allocated pointers in scoped_ptr:
169//
170// scoped_ptr<int, rtc::FreeDeleter> foo_ptr(
171// static_cast<int*>(malloc(sizeof(int))));
172struct FreeDeleter {
173 inline void operator()(void* ptr) const {
174 free(ptr);
175 }
176};
177
178namespace internal {
179
180// Minimal implementation of the core logic of scoped_ptr, suitable for
181// reuse in both scoped_ptr and its specializations.
182template <class T, class D>
183class scoped_ptr_impl {
184 public:
185 explicit scoped_ptr_impl(T* p) : data_(p) { }
186
187 // Initializer for deleters that have data parameters.
188 scoped_ptr_impl(T* p, const D& d) : data_(p, d) {}
189
190 // Templated constructor that destructively takes the value from another
191 // scoped_ptr_impl.
192 template <typename U, typename V>
193 scoped_ptr_impl(scoped_ptr_impl<U, V>* other)
194 : data_(other->release(), other->get_deleter()) {
195 // We do not support move-only deleters. We could modify our move
196 // emulation to have rtc::subtle::move() and
197 // rtc::subtle::forward()
198 // functions that are imperfect emulations of their C++11 equivalents,
199 // but until there's a requirement, just assume deleters are copyable.
200 }
201
202 template <typename U, typename V>
203 void TakeState(scoped_ptr_impl<U, V>* other) {
204 // See comment in templated constructor above regarding lack of support
205 // for move-only deleters.
206 reset(other->release());
207 get_deleter() = other->get_deleter();
208 }
209
210 ~scoped_ptr_impl() {
211 if (data_.ptr != NULL) {
212 // Not using get_deleter() saves one function call in non-optimized
213 // builds.
214 static_cast<D&>(data_)(data_.ptr);
215 }
216 }
217
218 void reset(T* p) {
219 // This is a self-reset, which is no longer allowed: http://crbug.com/162971
220 if (p != NULL && p == data_.ptr)
221 abort();
222
223 // Note that running data_.ptr = p can lead to undefined behavior if
224 // get_deleter()(get()) deletes this. In order to pevent this, reset()
225 // should update the stored pointer before deleting its old value.
226 //
227 // However, changing reset() to use that behavior may cause current code to
228 // break in unexpected ways. If the destruction of the owned object
229 // dereferences the scoped_ptr when it is destroyed by a call to reset(),
230 // then it will incorrectly dispatch calls to |p| rather than the original
231 // value of |data_.ptr|.
232 //
233 // During the transition period, set the stored pointer to NULL while
234 // deleting the object. Eventually, this safety check will be removed to
235 // prevent the scenario initially described from occuring and
236 // http://crbug.com/176091 can be closed.
237 T* old = data_.ptr;
238 data_.ptr = NULL;
239 if (old != NULL)
240 static_cast<D&>(data_)(old);
241 data_.ptr = p;
242 }
243
244 T* get() const { return data_.ptr; }
245
246 D& get_deleter() { return data_; }
247 const D& get_deleter() const { return data_; }
248
249 void swap(scoped_ptr_impl& p2) {
250 // Standard swap idiom: 'using std::swap' ensures that std::swap is
251 // present in the overload set, but we call swap unqualified so that
252 // any more-specific overloads can be used, if available.
253 using std::swap;
254 swap(static_cast<D&>(data_), static_cast<D&>(p2.data_));
255 swap(data_.ptr, p2.data_.ptr);
256 }
257
258 T* release() {
259 T* old_ptr = data_.ptr;
260 data_.ptr = NULL;
261 return old_ptr;
262 }
263
264 T** accept() {
265 reset(NULL);
266 return &(data_.ptr);
267 }
268
269 T** use() {
270 return &(data_.ptr);
271 }
272
273 private:
274 // Needed to allow type-converting constructor.
275 template <typename U, typename V> friend class scoped_ptr_impl;
276
277 // Use the empty base class optimization to allow us to have a D
278 // member, while avoiding any space overhead for it when D is an
279 // empty class. See e.g. http://www.cantrip.org/emptyopt.html for a good
280 // discussion of this technique.
281 struct Data : public D {
282 explicit Data(T* ptr_in) : ptr(ptr_in) {}
283 Data(T* ptr_in, const D& other) : D(other), ptr(ptr_in) {}
284 T* ptr;
285 };
286
287 Data data_;
288
289 DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl);
290};
291
292} // namespace internal
293
294// A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
295// automatically deletes the pointer it holds (if any).
296// That is, scoped_ptr<T> owns the T object that it points to.
297// Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object.
298// Also like T*, scoped_ptr<T> is thread-compatible, and once you
299// dereference it, you get the thread safety guarantees of T.
300//
301// The size of scoped_ptr is small. On most compilers, when using the
302// DefaultDeleter, sizeof(scoped_ptr<T>) == sizeof(T*). Custom deleters will
303// increase the size proportional to whatever state they need to have. See
304// comments inside scoped_ptr_impl<> for details.
305//
306// Current implementation targets having a strict subset of C++11's
307// unique_ptr<> features. Known deficiencies include not supporting move-only
308// deleteres, function pointers as deleters, and deleters with reference
309// types.
310template <class T, class D = rtc::DefaultDeleter<T> >
311class scoped_ptr {
312 TALK_MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue)
313
314 public:
315 // The element and deleter types.
316 typedef T element_type;
317 typedef D deleter_type;
318
319 // Constructor. Defaults to initializing with NULL.
320 scoped_ptr() : impl_(NULL) { }
321
322 // Constructor. Takes ownership of p.
323 explicit scoped_ptr(element_type* p) : impl_(p) { }
324
325 // Constructor. Allows initialization of a stateful deleter.
326 scoped_ptr(element_type* p, const D& d) : impl_(p, d) { }
327
328 // Constructor. Allows construction from a scoped_ptr rvalue for a
329 // convertible type and deleter.
330 //
331 // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this constructor distinct
332 // from the normal move constructor. By C++11 20.7.1.2.1.21, this constructor
333 // has different post-conditions if D is a reference type. Since this
334 // implementation does not support deleters with reference type,
335 // we do not need a separate move constructor allowing us to avoid one
336 // use of SFINAE. You only need to care about this if you modify the
337 // implementation of scoped_ptr.
338 template <typename U, typename V>
339 scoped_ptr(scoped_ptr<U, V> other) : impl_(&other.impl_) {
340 COMPILE_ASSERT(!rtc::is_array<U>::value, U_cannot_be_an_array);
341 }
342
343 // Constructor. Move constructor for C++03 move emulation of this type.
344 scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { }
345
346 // operator=. Allows assignment from a scoped_ptr rvalue for a convertible
347 // type and deleter.
348 //
349 // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this operator= distinct from
350 // the normal move assignment operator. By C++11 20.7.1.2.3.4, this templated
351 // form has different requirements on for move-only Deleters. Since this
352 // implementation does not support move-only Deleters, we do not need a
353 // separate move assignment operator allowing us to avoid one use of SFINAE.
354 // You only need to care about this if you modify the implementation of
355 // scoped_ptr.
356 template <typename U, typename V>
357 scoped_ptr& operator=(scoped_ptr<U, V> rhs) {
358 COMPILE_ASSERT(!rtc::is_array<U>::value, U_cannot_be_an_array);
359 impl_.TakeState(&rhs.impl_);
360 return *this;
361 }
362
363 // Reset. Deletes the currently owned object, if any.
364 // Then takes ownership of a new object, if given.
365 void reset(element_type* p = NULL) { impl_.reset(p); }
366
367 // Accessors to get the owned object.
368 // operator* and operator-> will assert() if there is no current object.
369 element_type& operator*() const {
370 ASSERT(impl_.get() != NULL);
371 return *impl_.get();
372 }
373 element_type* operator->() const {
374 ASSERT(impl_.get() != NULL);
375 return impl_.get();
376 }
377 element_type* get() const { return impl_.get(); }
378
379 // Access to the deleter.
380 deleter_type& get_deleter() { return impl_.get_deleter(); }
381 const deleter_type& get_deleter() const { return impl_.get_deleter(); }
382
383 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
384 // implicitly convertible to a real bool (which is dangerous).
385 //
386 // Note that this trick is only safe when the == and != operators
387 // are declared explicitly, as otherwise "scoped_ptr1 ==
388 // scoped_ptr2" will compile but do the wrong thing (i.e., convert
389 // to Testable and then do the comparison).
390 private:
391 typedef rtc::internal::scoped_ptr_impl<element_type, deleter_type>
392 scoped_ptr::*Testable;
393
394 public:
395 operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; }
396
397 // Comparison operators.
398 // These return whether two scoped_ptr refer to the same object, not just to
399 // two different but equal objects.
400 bool operator==(const element_type* p) const { return impl_.get() == p; }
401 bool operator!=(const element_type* p) const { return impl_.get() != p; }
402
403 // Swap two scoped pointers.
404 void swap(scoped_ptr& p2) {
405 impl_.swap(p2.impl_);
406 }
407
408 // Release a pointer.
409 // The return value is the current pointer held by this object.
410 // If this object holds a NULL pointer, the return value is NULL.
411 // After this operation, this object will hold a NULL pointer,
412 // and will not own the object any more.
413 element_type* release() WARN_UNUSED_RESULT {
414 return impl_.release();
415 }
416
417 // Delete the currently held pointer and return a pointer
418 // to allow overwriting of the current pointer address.
419 element_type** accept() WARN_UNUSED_RESULT {
420 return impl_.accept();
421 }
422
423 // Return a pointer to the current pointer address.
424 element_type** use() WARN_UNUSED_RESULT {
425 return impl_.use();
426 }
427
428 // C++98 doesn't support functions templates with default parameters which
429 // makes it hard to write a PassAs() that understands converting the deleter
430 // while preserving simple calling semantics.
431 //
432 // Until there is a use case for PassAs() with custom deleters, just ignore
433 // the custom deleter.
434 template <typename PassAsType>
435 scoped_ptr<PassAsType> PassAs() {
436 return scoped_ptr<PassAsType>(Pass());
437 }
438
439 private:
440 // Needed to reach into |impl_| in the constructor.
441 template <typename U, typename V> friend class scoped_ptr;
442 rtc::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
443
444 // Forbidden for API compatibility with std::unique_ptr.
445 explicit scoped_ptr(int disallow_construction_from_null);
446
447 // Forbid comparison of scoped_ptr types. If U != T, it totally
448 // doesn't make sense, and if U == T, it still doesn't make sense
449 // because you should never have the same object owned by two different
450 // scoped_ptrs.
451 template <class U> bool operator==(scoped_ptr<U> const& p2) const;
452 template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
453};
454
455template <class T, class D>
456class scoped_ptr<T[], D> {
457 TALK_MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue)
458
459 public:
460 // The element and deleter types.
461 typedef T element_type;
462 typedef D deleter_type;
463
464 // Constructor. Defaults to initializing with NULL.
465 scoped_ptr() : impl_(NULL) { }
466
467 // Constructor. Stores the given array. Note that the argument's type
468 // must exactly match T*. In particular:
469 // - it cannot be a pointer to a type derived from T, because it is
470 // inherently unsafe in the general case to access an array through a
471 // pointer whose dynamic type does not match its static type (eg., if
472 // T and the derived types had different sizes access would be
473 // incorrectly calculated). Deletion is also always undefined
474 // (C++98 [expr.delete]p3). If you're doing this, fix your code.
475 // - it cannot be NULL, because NULL is an integral expression, not a
476 // pointer to T. Use the no-argument version instead of explicitly
477 // passing NULL.
478 // - it cannot be const-qualified differently from T per unique_ptr spec
479 // (http://cplusplus.github.com/LWG/lwg-active.html#2118). Users wanting
480 // to work around this may use implicit_cast<const T*>().
481 // However, because of the first bullet in this comment, users MUST
482 // NOT use implicit_cast<Base*>() to upcast the static type of the array.
483 explicit scoped_ptr(element_type* array) : impl_(array) { }
484
485 // Constructor. Move constructor for C++03 move emulation of this type.
486 scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { }
487
488 // operator=. Move operator= for C++03 move emulation of this type.
489 scoped_ptr& operator=(RValue rhs) {
490 impl_.TakeState(&rhs.object->impl_);
491 return *this;
492 }
493
494 // Reset. Deletes the currently owned array, if any.
495 // Then takes ownership of a new object, if given.
496 void reset(element_type* array = NULL) { impl_.reset(array); }
497
498 // Accessors to get the owned array.
499 element_type& operator[](size_t i) const {
500 ASSERT(impl_.get() != NULL);
501 return impl_.get()[i];
502 }
503 element_type* get() const { return impl_.get(); }
504
505 // Access to the deleter.
506 deleter_type& get_deleter() { return impl_.get_deleter(); }
507 const deleter_type& get_deleter() const { return impl_.get_deleter(); }
508
509 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
510 // implicitly convertible to a real bool (which is dangerous).
511 private:
512 typedef rtc::internal::scoped_ptr_impl<element_type, deleter_type>
513 scoped_ptr::*Testable;
514
515 public:
516 operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; }
517
518 // Comparison operators.
519 // These return whether two scoped_ptr refer to the same object, not just to
520 // two different but equal objects.
521 bool operator==(element_type* array) const { return impl_.get() == array; }
522 bool operator!=(element_type* array) const { return impl_.get() != array; }
523
524 // Swap two scoped pointers.
525 void swap(scoped_ptr& p2) {
526 impl_.swap(p2.impl_);
527 }
528
529 // Release a pointer.
530 // The return value is the current pointer held by this object.
531 // If this object holds a NULL pointer, the return value is NULL.
532 // After this operation, this object will hold a NULL pointer,
533 // and will not own the object any more.
534 element_type* release() WARN_UNUSED_RESULT {
535 return impl_.release();
536 }
537
538 // Delete the currently held pointer and return a pointer
539 // to allow overwriting of the current pointer address.
540 element_type** accept() WARN_UNUSED_RESULT {
541 return impl_.accept();
542 }
543
544 // Return a pointer to the current pointer address.
545 element_type** use() WARN_UNUSED_RESULT {
546 return impl_.use();
547 }
548
549 private:
550 // Force element_type to be a complete type.
551 enum { type_must_be_complete = sizeof(element_type) };
552
553 // Actually hold the data.
554 rtc::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
555
556 // Disable initialization from any type other than element_type*, by
557 // providing a constructor that matches such an initialization, but is
558 // private and has no definition. This is disabled because it is not safe to
559 // call delete[] on an array whose static type does not match its dynamic
560 // type.
561 template <typename U> explicit scoped_ptr(U* array);
562 explicit scoped_ptr(int disallow_construction_from_null);
563
564 // Disable reset() from any type other than element_type*, for the same
565 // reasons as the constructor above.
566 template <typename U> void reset(U* array);
567 void reset(int disallow_reset_from_null);
568
569 // Forbid comparison of scoped_ptr types. If U != T, it totally
570 // doesn't make sense, and if U == T, it still doesn't make sense
571 // because you should never have the same object owned by two different
572 // scoped_ptrs.
573 template <class U> bool operator==(scoped_ptr<U> const& p2) const;
574 template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
575};
576
577} // namespace rtc
578
579// Free functions
580template <class T, class D>
581void swap(rtc::scoped_ptr<T, D>& p1, rtc::scoped_ptr<T, D>& p2) {
582 p1.swap(p2);
583}
584
585template <class T, class D>
586bool operator==(T* p1, const rtc::scoped_ptr<T, D>& p2) {
587 return p1 == p2.get();
588}
589
590template <class T, class D>
591bool operator!=(T* p1, const rtc::scoped_ptr<T, D>& p2) {
592 return p1 != p2.get();
593}
594
595#endif // #ifndef WEBRTC_BASE_SCOPED_PTR_H__