1/* 2 * Copyright (c) 2013 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// Borrowed from Chromium's src/base/memory/scoped_ptr.h. 12 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[]. 17// 18// Example usage (scoped_ptr<T>): 19// { 20// scoped_ptr<Foo> foo(new Foo("wee")); 21// } // foo goes out of scope, releasing the pointer with it. 22// 23// { 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. 36// 37// Example usage (scoped_ptr<T[]>): 38// { 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. 42// } 43// 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: 51// 52// void TakesOwnership(scoped_ptr<Foo> arg) { 53// // Do something with arg 54// } 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")); 59// } 60// scoped_ptr<Foo> PassThru(scoped_ptr<Foo> arg) { 61// return arg.Pass(); 62// } 63// 64// { 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. 70// } 71// 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(). 78// 79// Pass() properly handles upcast in initialization, i.e. you can use a 80// scoped_ptr<Child> to initialize a scoped_ptr<Parent>: 81// 82// scoped_ptr<Foo> foo(new Foo()); 83// scoped_ptr<FooParent> parent(foo.Pass()); 84// 85// PassAs<>() should be used to upcast return value in return statement: 86// 87// scoped_ptr<Foo> CreateFoo() { 88// scoped_ptr<FooChild> result(new FooChild()); 89// return result.PassAs<Foo>(); 90// } 91// 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. 94 95#ifndef WEBRTC_SYSTEM_WRAPPERS_INTERFACE_SCOPED_PTR_H_ 96#define WEBRTC_SYSTEM_WRAPPERS_INTERFACE_SCOPED_PTR_H_ 97 98// This is an implementation designed to match the anticipated future TR2 99// implementation of the scoped_ptr class. 100 101#include <assert.h> 102#include <stddef.h> 103#include <stdlib.h> 104 105#include <algorithm> // For std::swap(). 106 107#include "webrtc/base/constructormagic.h" 108#include "webrtc/system_wrappers/interface/compile_assert.h" 109#include "webrtc/system_wrappers/interface/template_util.h" 110#include "webrtc/system_wrappers/source/move.h" 111#include "webrtc/typedefs.h" 112 113namespace webrtc { 114 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>. 118template <class T> 119struct DefaultDeleter { 120 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. 124 // 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 129 // misuses. 130 // 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); 138 } 139 inline void operator()(T* ptr) const { 140 enum { type_must_be_complete = sizeof(T) }; 141 delete ptr; 142 } 143}; 144 145// Specialization of DefaultDeleter for array types. 146template <class T> 147struct DefaultDeleter<T[]> { 148 inline void operator()(T* ptr) const { 149 enum { type_must_be_complete = sizeof(T) }; 150 delete[] ptr; 151 } 152 153 private: 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 156 // type. 157 // 158 // References: 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; 162}; 163 164template <class T, int n> 165struct 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); 168}; 169 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: 172// 173// scoped_ptr<int, webrtc::FreeDeleter> foo_ptr( 174// static_cast<int*>(malloc(sizeof(int)))); 175struct FreeDeleter { 176 inline void operator()(void* ptr) const { 177 free(ptr); 178 } 179}; 180 181namespace internal { 182 183// Minimal implementation of the core logic of scoped_ptr, suitable for 184// reuse in both scoped_ptr and its specializations. 185template <class T, class D> 186class scoped_ptr_impl { 187 public: 188 explicit scoped_ptr_impl(T* p) : data_(p) { } 189 190 // Initializer for deleters that have data parameters. 191 scoped_ptr_impl(T* p, const D& d) : data_(p, d) {} 192 193 // Templated constructor that destructively takes the value from another 194 // scoped_ptr_impl. 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. 202 } 203 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(); 210 } 211 212 ~scoped_ptr_impl() { 213 if (data_.ptr != NULL) { 214 // Not using get_deleter() saves one function call in non-optimized 215 // builds. 216 static_cast<D&>(data_)(data_.ptr); 217 } 218 } 219 220 void reset(T* p) { 221 // This is a self-reset, which is no longer allowed: http://crbug.com/162971 222 if (p != NULL && p == data_.ptr) 223 abort(); 224 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. 228 // 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|. 234 // 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. 239 T* old = data_.ptr; 240 data_.ptr = NULL; 241 if (old != NULL) 242 static_cast<D&>(data_)(old); 243 data_.ptr = p; 244 } 245 246 T* get() const { return data_.ptr; } 247 248 D& get_deleter() { return data_; } 249 const D& get_deleter() const { return data_; } 250 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. 255 using std::swap; 256 swap(static_cast<D&>(data_), static_cast<D&>(p2.data_)); 257 swap(data_.ptr, p2.data_.ptr); 258 } 259 260 T* release() { 261 T* old_ptr = data_.ptr; 262 data_.ptr = NULL; 263 return old_ptr; 264 } 265 266 private: 267 // Needed to allow type-converting constructor. 268 template <typename U, typename V> friend class scoped_ptr_impl; 269 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) {} 277 T* ptr; 278 }; 279 280 Data data_; 281 282 DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl); 283}; 284 285} // namespace internal 286 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. 293// 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. 298// 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 302// types. 303template <class T, class D = webrtc::DefaultDeleter<T> > 304class scoped_ptr { 305 WEBRTC_MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue) 306 307 public: 308 // The element and deleter types. 309 typedef T element_type; 310 typedef D deleter_type; 311 312 // Constructor. Defaults to initializing with NULL. 313 scoped_ptr() : impl_(NULL) { } 314 315 // Constructor. Takes ownership of p. 316 explicit scoped_ptr(element_type* p) : impl_(p) { } 317 318 // Constructor. Allows initialization of a stateful deleter. 319 scoped_ptr(element_type* p, const D& d) : impl_(p, d) { } 320 321 // Constructor. Allows construction from a scoped_ptr rvalue for a 322 // convertible type and deleter. 323 // 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); 334 } 335 336 // Constructor. Move constructor for C++03 move emulation of this type. 337 scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { } 338 339 // operator=. Allows assignment from a scoped_ptr rvalue for a convertible 340 // type and deleter. 341 // 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 348 // scoped_ptr. 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_); 353 return *this; 354 } 355 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); } 359 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); 364 return *impl_.get(); 365 } 366 element_type* operator->() const { 367 assert(impl_.get() != NULL); 368 return impl_.get(); 369 } 370 element_type* get() const { return impl_.get(); } 371 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(); } 375 376 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not 377 // implicitly convertible to a real bool (which is dangerous). 378 // 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). 383 private: 384 typedef webrtc::internal::scoped_ptr_impl<element_type, deleter_type> 385 scoped_ptr::*Testable; 386 387 public: 388 operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; } 389 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; } 395 396 // Swap two scoped pointers. 397 void swap(scoped_ptr& p2) { 398 impl_.swap(p2.impl_); 399 } 400 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(); 408 } 409 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. 413 // 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()); 419 } 420 421 private: 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_; 425 426 // Forbidden for API compatibility with std::unique_ptr. 427 explicit scoped_ptr(int disallow_construction_from_null); 428 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 432 // scoped_ptrs. 433 template <class U> bool operator==(scoped_ptr<U> const& p2) const; 434 template <class U> bool operator!=(scoped_ptr<U> const& p2) const; 435}; 436 437template <class T, class D> 438class scoped_ptr<T[], D> { 439 WEBRTC_MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue) 440 441 public: 442 // The element and deleter types. 443 typedef T element_type; 444 typedef D deleter_type; 445 446 // Constructor. Defaults to initializing with NULL. 447 scoped_ptr() : impl_(NULL) { } 448 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 459 // passing NULL. 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) { } 466 467 // Constructor. Move constructor for C++03 move emulation of this type. 468 scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { } 469 470 // operator=. Move operator= for C++03 move emulation of this type. 471 scoped_ptr& operator=(RValue rhs) { 472 impl_.TakeState(&rhs.object->impl_); 473 return *this; 474 } 475 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); } 479 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]; 484 } 485 element_type* get() const { return impl_.get(); } 486 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(); } 490 491 // Allow scoped_ptr<element_type> to be used in boolean expressions, but not 492 // implicitly convertible to a real bool (which is dangerous). 493 private: 494 typedef webrtc::internal::scoped_ptr_impl<element_type, deleter_type> 495 scoped_ptr::*Testable; 496 497 public: 498 operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; } 499 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; } 505 506 // Swap two scoped pointers. 507 void swap(scoped_ptr& p2) { 508 impl_.swap(p2.impl_); 509 } 510 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(); 518 } 519 520 private: 521 // Force element_type to be a complete type. 522 enum { type_must_be_complete = sizeof(element_type) }; 523 524 // Actually hold the data. 525 webrtc::internal::scoped_ptr_impl<element_type, deleter_type> impl_; 526 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 531 // type. 532 template <typename U> explicit scoped_ptr(U* array); 533 explicit scoped_ptr(int disallow_construction_from_null); 534 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); 539 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 543 // scoped_ptrs. 544 template <class U> bool operator==(scoped_ptr<U> const& p2) const; 545 template <class U> bool operator!=(scoped_ptr<U> const& p2) const; 546}; 547 548} // namespace webrtc 549 550// Free functions 551template <class T, class D> 552void swap(webrtc::scoped_ptr<T, D>& p1, webrtc::scoped_ptr<T, D>& p2) { 553 p1.swap(p2); 554} 555 556template <class T, class D> 557bool operator==(T* p1, const webrtc::scoped_ptr<T, D>& p2) { 558 return p1 == p2.get(); 559} 560 561template <class T, class D> 562bool operator!=(T* p1, const webrtc::scoped_ptr<T, D>& p2) { 563 return p1 != p2.get(); 564} 565 566#endif // WEBRTC_SYSTEM_WRAPPERS_INTERFACE_SCOPED_PTR_H_ 567