1 /* 2 Copyright 2011 Google Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 18 #ifndef SkTLazy_DEFINED 19 #define SkTLazy_DEFINED 20 21 #include "SkTypes.h" 22 23 /** 24 * Efficient way to defer allocating/initializing a class until it is needed 25 * (if ever). 26 */ 27 template <typename T> class SkTLazy { 28 public: SkTLazy()29 SkTLazy() : fPtr(NULL) {} 30 SkTLazy(const T * src)31 explicit SkTLazy(const T* src) : fPtr(NULL) { 32 if (src) { 33 fPtr = new (fStorage) T(*src); 34 } 35 } 36 SkTLazy(const SkTLazy<T> & src)37 SkTLazy(const SkTLazy<T>& src) : fPtr(NULL) { 38 const T* ptr = src.get(); 39 if (ptr) { 40 fPtr = new (fStorage) T(*ptr); 41 } 42 } 43 ~SkTLazy()44 ~SkTLazy() { 45 if (fPtr) { 46 fPtr->~T(); 47 } 48 } 49 50 /** 51 * Return a pointer to a default-initialized instance of the class. If a 52 * previous instance had been initialzied (either from init() or set()) it 53 * will first be destroyed, so that a freshly initialized instance is 54 * always returned. 55 */ init()56 T* init() { 57 if (fPtr) { 58 fPtr->~T(); 59 } 60 fPtr = new (fStorage) T; 61 return fPtr; 62 } 63 64 /** 65 * Copy src into this, and return a pointer to a copy of it. Note this 66 * will always return the same pointer, so if it is called on a lazy that 67 * has already been initialized, then this will copy over the previous 68 * contents. 69 */ set(const T & src)70 T* set(const T& src) { 71 if (fPtr) { 72 *fPtr = src; 73 } else { 74 fPtr = new (fStorage) T(src); 75 } 76 return fPtr; 77 } 78 79 /** 80 * Returns either NULL, or a copy of the object that was passed to 81 * set() or the constructor. 82 */ get()83 T* get() const { return fPtr; } 84 85 private: 86 T* fPtr; // NULL or fStorage 87 char fStorage[sizeof(T)]; 88 }; 89 90 #endif 91 92