• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_MAC_SCOPED_NSAUTORELEASE_POOL_H_
6 #define BASE_MAC_SCOPED_NSAUTORELEASE_POOL_H_
7 
8 #include "base/base_export.h"
9 #include "base/memory/raw_ptr_exclusion.h"
10 #include "base/threading/thread_checker.h"
11 
12 namespace base::mac {
13 
14 // ScopedNSAutoreleasePool creates an autorelease pool when instantiated and
15 // pops it when destroyed.  This allows an autorelease pool to be maintained in
16 // ordinary C++ code without bringing in any direct Objective-C dependency.
17 //
18 // Before using, please be aware that the semantics of autorelease pools do not
19 // match the semantics of a C++ class. In particular, recycling or destructing a
20 // pool lower on the stack destroys all pools higher on the stack, which does
21 // not mesh well with the existence of C++ objects for each pool.
22 //
23 // TODO(https://crbug.com/1424190): Enforce stack-only use via the
24 // STACK_ALLOCATED annotation.
25 //
26 // Use this class only in C++ code; use @autoreleasepool in Obj-C(++) code.
27 
28 class BASE_EXPORT ScopedNSAutoreleasePool {
29  public:
30   ScopedNSAutoreleasePool();
31 
32   ScopedNSAutoreleasePool(const ScopedNSAutoreleasePool&) = delete;
33   ScopedNSAutoreleasePool& operator=(const ScopedNSAutoreleasePool&) = delete;
34   ScopedNSAutoreleasePool(ScopedNSAutoreleasePool&&) = delete;
35   ScopedNSAutoreleasePool& operator=(ScopedNSAutoreleasePool&&) = delete;
36 
37   ~ScopedNSAutoreleasePool();
38 
39   // Clear out the pool in case its position on the stack causes it to be alive
40   // for long periods of time (such as the entire length of the app). Only use
41   // then when you're certain the items currently in the pool are no longer
42   // needed.
43   void Recycle();
44 
45  private:
46   // This field is not a raw_ptr<> because it is a pointer to an Objective-C
47   // object.
48   RAW_PTR_EXCLUSION void* autorelease_pool_ GUARDED_BY_CONTEXT(thread_checker_);
49 
50   THREAD_CHECKER(thread_checker_);
51 };
52 
53 }  // namespace base::mac
54 
55 #endif  // BASE_MAC_SCOPED_NSAUTORELEASE_POOL_H_
56