1// Copyright 2014 The Android Open Source Project 2// 3// This software is licensed under the terms of the GNU General Public 4// License version 2, as published by the Free Software Foundation, and 5// may be copied, distributed, and modified under those terms. 6// 7// This program is distributed in the hope that it will be useful, 8// but WITHOUT ANY WARRANTY; without even the implied warranty of 9// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10// GNU General Public License for more details. 11 12#ifndef ANDROID_BASE_MEMORY_SCOPED_PTR_H 13#define ANDROID_BASE_MEMORY_SCOPED_PTR_H 14 15#include "android/base/Compiler.h" 16 17#include <stddef.h> 18 19namespace android { 20namespace base { 21 22// Helper scoped pointer template class. Ensures that an object is 23// deleted at scope exit, unless its release() method has been called. 24// Usage example: 25// 26// { 27// ScopedPtr<Foo> ptr(new Foo()); 28// foo->DoStuff(); 29// } // destroys the instance automatically. 30// 31// You cannot copy ScopedPtr instances directly, but you can actually 32// pass ownership from one instance to the other with the release() 33// method as in: 34// 35// ScopedPtr<Foo> ptr(new Foo()); // object owned by |ptr| 36// ScopedPtr<Foo> ptr2(ptr.release()); // object owned by |ptr2| 37// 38template <class T> 39class ScopedPtr { 40public: 41 // Default constructor. 42 ScopedPtr() : mPtr(NULL) {} 43 44 // Normal constructor, takes ownership of |ptr|. 45 explicit ScopedPtr(T* ptr) : mPtr(ptr) {} 46 47 // Destructor will call reset() automatically. 48 ~ScopedPtr() { reset(NULL); } 49 50 // Release the pointer object from the instance and return it. 51 // Caller should assume ownership of the object. 52 T* release() { 53 T* ptr = mPtr; 54 mPtr = NULL; 55 return ptr; 56 } 57 58 // Reset the managed object to a new value. 59 void reset(T* ptr) { 60 delete mPtr; 61 mPtr = ptr; 62 } 63 64 // Return pointer of scoped object. Owernship is _not_ 65 // transferred to the caller. 66 T* get() { return mPtr; } 67 68 // Return a reference to the scoped object. Allows one to 69 // write (*foo).DoStuff(). 70 T& operator*() { return *mPtr; } 71 72 // Return a pointer to the scoped object. Allows one to write 73 // foo->DoStuff(). 74 T* operator->() { return mPtr; } 75 76private: 77 DISALLOW_COPY_AND_ASSIGN(ScopedPtr); 78 T* mPtr; 79}; 80 81} // namespace base 82} // namespace android 83 84#endif // ANDROID_BASE_MEMORY_SCOPED_PTR_H 85