Branch data Line data Source code
1 : : /* Template for deferring object creation until the object is needed.
2 : : Copyright (C) 2024-2025 Free Software Foundation, Inc.
3 : : Contributed by David Malcolm <dmalcolm@redhat.com>
4 : :
5 : : This file is part of GCC.
6 : :
7 : : GCC is free software; you can redistribute it and/or modify it under
8 : : the terms of the GNU General Public License as published by the Free
9 : : Software Foundation; either version 3, or (at your option) any later
10 : : version.
11 : :
12 : : GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 : : WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 : : FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 : : for more details.
16 : :
17 : : You should have received a copy of the GNU General Public License
18 : : along with GCC; see the file COPYING3. If not see
19 : : <http://www.gnu.org/licenses/>. */
20 : :
21 : : #ifndef GCC_LAZILY_CREATED_H
22 : : #define GCC_LAZILY_CREATED_H
23 : :
24 : : /* A template for deferring object creation for a type T until the object
25 : : is needed, to avoid potentially expensive creation of T unless it's
26 : : actually needed (e.g. for directed graphs associated with a diagnostic,
27 : : which are ignored by the default "text" sink). */
28 : :
29 : : template <typename T>
30 : : class lazily_created
31 : : {
32 : : public:
33 : : virtual ~lazily_created () {}
34 : :
35 : : const T &
36 : 4 : get_or_create () const
37 : : {
38 : 4 : if (!m_object)
39 : 4 : m_object = create_object ();
40 : 4 : gcc_assert (m_object);
41 : 4 : return *m_object;
42 : : }
43 : :
44 : : private:
45 : : virtual std::unique_ptr<T>
46 : : create_object () const = 0;
47 : :
48 : : mutable std::unique_ptr<T> m_object;
49 : : };
50 : :
51 : : #endif /* ! GCC_LAZILY_CREATED_H */
|