blob: 2aa1b321d8b73c9b8436f29bbc40992ba80bda28 [file] [log] [blame]
Vitaly Bukacbed2062015-08-17 12:54:05 -07001// 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.
4
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[].
9//
10// Example usage (scoped_ptr<T>):
11// {
12// scoped_ptr<Foo> foo(new Foo("wee"));
13// } // foo goes out of scope, releasing the pointer with it.
14//
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.
28//
29// Example usage (scoped_ptr<T[]>):
30// {
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.
34// }
35//
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:
43//
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// }
55//
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 nullptr.
62// }
63//
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().
70//
71// Pass() properly handles upcast in initialization, i.e. you can use a
72// scoped_ptr<Child> to initialize a scoped_ptr<Parent>:
73//
74// scoped_ptr<Foo> foo(new Foo());
75// scoped_ptr<FooParent> parent(foo.Pass());
76
77#ifndef BASE_MEMORY_SCOPED_PTR_H_
78#define BASE_MEMORY_SCOPED_PTR_H_
79
80// This is an implementation designed to match the anticipated future TR2
81// implementation of the scoped_ptr class.
82
83#include <assert.h>
84#include <stddef.h>
85#include <stdlib.h>
86
87#include <algorithm> // For std::swap().
88#include <iosfwd>
89
90#include "base/basictypes.h"
91#include "base/compiler_specific.h"
92#include "base/move.h"
93#include "base/template_util.h"
94
95namespace base {
96
97namespace subtle {
98class RefCountedBase;
99class RefCountedThreadSafeBase;
100} // namespace subtle
101
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>.
105template <class T>
106struct DefaultDeleter {
107 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.
111 //
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
116 // misuses.
117 //
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) };
Vitaly Buka8750b272015-08-18 18:39:08 -0700123 COMPILE_ASSERT((std::is_convertible<U*, T*>::value),
Vitaly Bukacbed2062015-08-17 12:54:05 -0700124 U_ptr_must_implicitly_convert_to_T_ptr);
125 }
126 inline void operator()(T* ptr) const {
127 enum { type_must_be_complete = sizeof(T) };
128 delete ptr;
129 }
130};
131
132// Specialization of DefaultDeleter for array types.
133template <class T>
134struct DefaultDeleter<T[]> {
135 inline void operator()(T* ptr) const {
136 enum { type_must_be_complete = sizeof(T) };
137 delete[] ptr;
138 }
139
140 private:
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
143 // type.
144 //
145 // References:
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;
149};
150
151template <class T, int n>
152struct 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);
155};
156
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:
159//
160// scoped_ptr<int, base::FreeDeleter> foo_ptr(
161// static_cast<int*>(malloc(sizeof(int))));
162struct FreeDeleter {
163 inline void operator()(void* ptr) const {
164 free(ptr);
165 }
166};
167
168namespace internal {
169
170template <typename T> struct IsNotRefCounted {
171 enum {
Vitaly Buka8750b272015-08-18 18:39:08 -0700172 value = !std::is_convertible<T*, base::subtle::RefCountedBase*>::value &&
173 !std::is_convertible<T*, base::subtle::RefCountedThreadSafeBase*>::
Vitaly Bukacbed2062015-08-17 12:54:05 -0700174 value
175 };
176};
177
178template <typename T>
179struct ShouldAbortOnSelfReset {
180 template <typename U>
181 static NoType Test(const typename U::AllowSelfReset*);
182
183 template <typename U>
184 static YesType Test(...);
185
186 static const bool value = sizeof(Test<T>(0)) == sizeof(YesType);
187};
188
189// Minimal implementation of the core logic of scoped_ptr, suitable for
190// reuse in both scoped_ptr and its specializations.
191template <class T, class D>
192class scoped_ptr_impl {
193 public:
194 explicit scoped_ptr_impl(T* p) : data_(p) {}
195
196 // Initializer for deleters that have data parameters.
197 scoped_ptr_impl(T* p, const D& d) : data_(p, d) {}
198
199 // Templated constructor that destructively takes the value from another
200 // scoped_ptr_impl.
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.
208 }
209
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();
216 }
217
218 ~scoped_ptr_impl() {
219 if (data_.ptr != nullptr) {
220 // Not using get_deleter() saves one function call in non-optimized
221 // builds.
222 static_cast<D&>(data_)(data_.ptr);
223 }
224 }
225
226 void reset(T* p) {
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);
230
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.
234 //
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|.
240 //
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.
245 T* old = data_.ptr;
246 data_.ptr = nullptr;
247 if (old != nullptr)
248 static_cast<D&>(data_)(old);
249 data_.ptr = p;
250 }
251
252 T* get() const { return data_.ptr; }
253
254 D& get_deleter() { return data_; }
255 const D& get_deleter() const { return data_; }
256
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.
261 using std::swap;
262 swap(static_cast<D&>(data_), static_cast<D&>(p2.data_));
263 swap(data_.ptr, p2.data_.ptr);
264 }
265
266 T* release() {
267 T* old_ptr = data_.ptr;
268 data_.ptr = nullptr;
269 return old_ptr;
270 }
271
272 private:
273 // Needed to allow type-converting constructor.
274 template <typename U, typename V> friend class scoped_ptr_impl;
275
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) {}
283 T* ptr;
284 };
285
286 Data data_;
287
288 DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl);
289};
290
291} // namespace internal
292
293} // namespace base
294
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.
301//
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.
306//
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
310// types.
311template <class T, class D = base::DefaultDeleter<T> >
312class scoped_ptr {
313 MOVE_ONLY_TYPE_WITH_MOVE_CONSTRUCTOR_FOR_CPP_03(scoped_ptr)
314
315 COMPILE_ASSERT(base::internal::IsNotRefCounted<T>::value,
316 T_is_refcounted_type_and_needs_scoped_refptr);
317
318 public:
319 // The element and deleter types.
320 typedef T element_type;
321 typedef D deleter_type;
322
323 // Constructor. Defaults to initializing with nullptr.
324 scoped_ptr() : impl_(nullptr) {}
325
326 // Constructor. Takes ownership of p.
327 explicit scoped_ptr(element_type* p) : impl_(p) {}
328
329 // Constructor. Allows initialization of a stateful deleter.
330 scoped_ptr(element_type* p, const D& d) : impl_(p, d) {}
331
332 // Constructor. Allows construction from a nullptr.
333 scoped_ptr(decltype(nullptr)) : impl_(nullptr) {}
334
335 // Constructor. Allows construction from a scoped_ptr rvalue for a
336 // convertible type and deleter.
337 //
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_) {
Vitaly Buka8750b272015-08-18 18:39:08 -0700348 COMPILE_ASSERT(!std::is_array<U>::value, U_cannot_be_an_array);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700349 }
350
351 // operator=. Allows assignment from a scoped_ptr rvalue for a convertible
352 // type and deleter.
353 //
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
360 // scoped_ptr.
361 template <typename U, typename V>
362 scoped_ptr& operator=(scoped_ptr<U, V>&& rhs) {
Vitaly Buka8750b272015-08-18 18:39:08 -0700363 COMPILE_ASSERT(!std::is_array<U>::value, U_cannot_be_an_array);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700364 impl_.TakeState(&rhs.impl_);
365 return *this;
366 }
367
368 // operator=. Allows assignment from a nullptr. Deletes the currently owned
369 // object, if any.
370 scoped_ptr& operator=(decltype(nullptr)) {
371 reset();
372 return *this;
373 }
374
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); }
378
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);
383 return *impl_.get();
384 }
385 element_type* operator->() const {
386 assert(impl_.get() != nullptr);
387 return impl_.get();
388 }
389 element_type* get() const { return impl_.get(); }
390
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(); }
394
395 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
396 // implicitly convertible to a real bool (which is dangerous).
397 //
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).
402 private:
403 typedef base::internal::scoped_ptr_impl<element_type, deleter_type>
404 scoped_ptr::*Testable;
405
406 public:
407 operator Testable() const {
408 return impl_.get() ? &scoped_ptr::impl_ : nullptr;
409 }
410
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; }
416
417 // Swap two scoped pointers.
418 void swap(scoped_ptr& p2) {
419 impl_.swap(p2.impl_);
420 }
421
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();
428 }
429
430 private:
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_;
434
435 // Forbidden for API compatibility with std::unique_ptr.
436 explicit scoped_ptr(int disallow_construction_from_null);
437
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
441 // scoped_ptrs.
442 template <class U> bool operator==(scoped_ptr<U> const& p2) const;
443 template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
444};
445
446template <class T, class D>
447class scoped_ptr<T[], D> {
448 MOVE_ONLY_TYPE_WITH_MOVE_CONSTRUCTOR_FOR_CPP_03(scoped_ptr)
449
450 public:
451 // The element and deleter types.
452 typedef T element_type;
453 typedef D deleter_type;
454
455 // Constructor. Defaults to initializing with nullptr.
456 scoped_ptr() : impl_(nullptr) {}
457
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 implicit_cast<const T*>().
469 // However, because of the first bullet in this comment, users MUST
470 // NOT use implicit_cast<Base*>() to upcast the static type of the array.
471 explicit scoped_ptr(element_type* array) : impl_(array) {}
472
473 // Constructor. Allows construction from a nullptr.
474 scoped_ptr(decltype(nullptr)) : impl_(nullptr) {}
475
476 // Constructor. Allows construction from a scoped_ptr rvalue.
477 scoped_ptr(scoped_ptr&& other) : impl_(&other.impl_) {}
478
479 // operator=. Allows assignment from a scoped_ptr rvalue.
480 scoped_ptr& operator=(scoped_ptr&& rhs) {
481 impl_.TakeState(&rhs.impl_);
482 return *this;
483 }
484
485 // operator=. Allows assignment from a nullptr. Deletes the currently owned
486 // array, if any.
487 scoped_ptr& operator=(decltype(nullptr)) {
488 reset();
489 return *this;
490 }
491
492 // Reset. Deletes the currently owned array, if any.
493 // Then takes ownership of a new object, if given.
494 void reset(element_type* array = nullptr) { impl_.reset(array); }
495
496 // Accessors to get the owned array.
497 element_type& operator[](size_t i) const {
498 assert(impl_.get() != nullptr);
499 return impl_.get()[i];
500 }
501 element_type* get() const { return impl_.get(); }
502
503 // Access to the deleter.
504 deleter_type& get_deleter() { return impl_.get_deleter(); }
505 const deleter_type& get_deleter() const { return impl_.get_deleter(); }
506
507 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
508 // implicitly convertible to a real bool (which is dangerous).
509 private:
510 typedef base::internal::scoped_ptr_impl<element_type, deleter_type>
511 scoped_ptr::*Testable;
512
513 public:
514 operator Testable() const {
515 return impl_.get() ? &scoped_ptr::impl_ : nullptr;
516 }
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. If this object
531 // holds a nullptr, the return value is nullptr. After this operation, this
532 // object will hold a nullptr, and will not own the object any more.
533 element_type* release() WARN_UNUSED_RESULT {
534 return impl_.release();
535 }
536
537 private:
538 // Force element_type to be a complete type.
539 enum { type_must_be_complete = sizeof(element_type) };
540
541 // Actually hold the data.
542 base::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
543
544 // Disable initialization from any type other than element_type*, by
545 // providing a constructor that matches such an initialization, but is
546 // private and has no definition. This is disabled because it is not safe to
547 // call delete[] on an array whose static type does not match its dynamic
548 // type.
549 template <typename U> explicit scoped_ptr(U* array);
550 explicit scoped_ptr(int disallow_construction_from_null);
551
552 // Disable reset() from any type other than element_type*, for the same
553 // reasons as the constructor above.
554 template <typename U> void reset(U* array);
555 void reset(int disallow_reset_from_null);
556
557 // Forbid comparison of scoped_ptr types. If U != T, it totally
558 // doesn't make sense, and if U == T, it still doesn't make sense
559 // because you should never have the same object owned by two different
560 // scoped_ptrs.
561 template <class U> bool operator==(scoped_ptr<U> const& p2) const;
562 template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
563};
564
565// Free functions
566template <class T, class D>
567void swap(scoped_ptr<T, D>& p1, scoped_ptr<T, D>& p2) {
568 p1.swap(p2);
569}
570
571template <class T, class D>
572bool operator==(T* p1, const scoped_ptr<T, D>& p2) {
573 return p1 == p2.get();
574}
575
576template <class T, class D>
577bool operator!=(T* p1, const scoped_ptr<T, D>& p2) {
578 return p1 != p2.get();
579}
580
581// A function to convert T* into scoped_ptr<T>
582// Doing e.g. make_scoped_ptr(new FooBarBaz<type>(arg)) is a shorter notation
583// for scoped_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
584template <typename T>
585scoped_ptr<T> make_scoped_ptr(T* ptr) {
586 return scoped_ptr<T>(ptr);
587}
588
589template <typename T>
590std::ostream& operator<<(std::ostream& out, const scoped_ptr<T>& p) {
591 return out << p.get();
592}
593
594#endif // BASE_MEMORY_SCOPED_PTR_H_