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