• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 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_TYPES_PASS_KEY_H_
6 #define BASE_TYPES_PASS_KEY_H_
7 
8 namespace base {
9 
10 // base::PassKey can be used to restrict access to functions to an authorized
11 // caller. The primary use case is restricting the construction of an object in
12 // situations where the constructor needs to be public, which may be the case
13 // if the object must be constructed through a helper function, such as
14 // blink::MakeGarbageCollected.
15 //
16 // For example, to limit the creation of 'Foo' to the 'Manager' class:
17 //
18 //  class Foo {
19 //   public:
20 //    Foo(base::PassKey<Manager>);
21 //  };
22 //
23 //  class Manager {
24 //   public:
25 //    using PassKey = base::PassKey<Manager>;
26 //    Manager() : foo_(blink::MakeGarbageCollected<Foo>(PassKey())) {}
27 //    void Trace(blink::Visitor* visitor) const { visitor->Trace(foo_); }
28 //    Foo* GetFooSingleton() { foo_; }
29 //
30 //   private:
31 //    blink::Member<Foo> foo_;
32 //  };
33 //
34 // In the above example, the 'Foo' constructor requires an instance of
35 // base::PassKey<Manager>. Only Manager is allowed to create such instances,
36 // making the constructor unusable elsewhere.
37 template <typename T>
38 class PassKey {
39  private:
40   // Avoid =default to disallow creation by uniform initialization.
PassKey()41   PassKey() {}
42 
43   friend T;
44 };
45 
46 }  // namespace base
47 
48 #endif  // BASE_TYPES_PASS_KEY_H_
49