1 // Copyright 2011 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_APPLE_SCOPED_NSAUTORELEASE_POOL_H_ 6 #define BASE_APPLE_SCOPED_NSAUTORELEASE_POOL_H_ 7 8 #include "base/base_export.h" 9 #include "base/dcheck_is_on.h" 10 #include "base/memory/raw_ptr_exclusion.h" 11 #include "base/memory/stack_allocated.h" 12 #include "base/thread_annotations.h" 13 #include "base/threading/thread_checker.h" 14 15 namespace base::apple { 16 17 // ScopedNSAutoreleasePool creates an autorelease pool when instantiated and 18 // pops it when destroyed. This allows an autorelease pool to be maintained in 19 // ordinary C++ code without bringing in any direct Objective-C dependency. 20 // 21 // Before using, please be aware that the semantics of autorelease pools do not 22 // match the semantics of a C++ class. In particular, recycling or destructing a 23 // pool lower on the stack destroys all pools higher on the stack, which does 24 // not mesh well with the existence of C++ objects for each pool. 25 // 26 // Use this class only in C++ code; use @autoreleasepool in Obj-C(++) code. 27 28 class BASE_EXPORT ScopedNSAutoreleasePool { 29 STACK_ALLOCATED(); 30 31 public: 32 ScopedNSAutoreleasePool(); 33 34 ScopedNSAutoreleasePool(const ScopedNSAutoreleasePool&) = delete; 35 ScopedNSAutoreleasePool& operator=(const ScopedNSAutoreleasePool&) = delete; 36 ScopedNSAutoreleasePool(ScopedNSAutoreleasePool&&) = delete; 37 ScopedNSAutoreleasePool& operator=(ScopedNSAutoreleasePool&&) = delete; 38 39 ~ScopedNSAutoreleasePool(); 40 41 // Clear out the pool in case its position on the stack causes it to be alive 42 // for long periods of time (such as the entire length of the app). Only use 43 // then when you're certain the items currently in the pool are no longer 44 // needed. 45 void Recycle(); 46 47 private: 48 // Pushes the autorelease pool and does all required verification. 49 void PushImpl() VALID_CONTEXT_REQUIRED(thread_checker_); 50 51 // Pops the autorelease pool and does all required verification. 52 void PopImpl() VALID_CONTEXT_REQUIRED(thread_checker_); 53 54 // This field is not a raw_ptr<> because it is a pointer to an Objective-C 55 // object. 56 RAW_PTR_EXCLUSION void* autorelease_pool_ GUARDED_BY_CONTEXT(thread_checker_); 57 58 THREAD_CHECKER(thread_checker_); 59 60 #if DCHECK_IS_ON() 61 unsigned long level_ = 0; 62 #endif 63 }; 64 65 } // namespace base::apple 66 67 #endif // BASE_APPLE_SCOPED_NSAUTORELEASE_POOL_H_ 68