1 /* A safe iterator for GDB, the GNU debugger.
2 Copyright (C) 2018-2019 Free Software Foundation, Inc.
4 This file is part of GDB.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 #ifndef COMMON_SAFE_ITERATOR_H
20 #define COMMON_SAFE_ITERATOR_H
22 /* A forward iterator that wraps Iterator, such that when iterating
23 with iterator IT, it is possible to delete *IT without invalidating
24 IT. Suitably wrapped in a range type and used with range-for, this
25 allow convenient patterns like this:
27 // range_safe() returns a range type whose begin()/end() methods
28 // return safe iterators.
29 for (foo *f : range_safe ())
31 if (f->should_delete ())
33 // The ++it operation implicitly done by the range-for is
34 // still OK after this.
40 template<typename Iterator
>
41 class basic_safe_iterator
44 typedef basic_safe_iterator self_type
;
45 typedef typename
Iterator::value_type value_type
;
46 typedef typename
Iterator::reference reference
;
47 typedef typename
Iterator::pointer pointer
;
48 typedef typename
Iterator::iterator_category iterator_category
;
49 typedef typename
Iterator::difference_type difference_type
;
51 /* Construct by forwarding all arguments to the underlying
53 template<typename
... Args
>
54 explicit basic_safe_iterator (Args
&&...args
)
55 : m_it (std::forward
<Args
> (args
)...),
62 /* Create a one-past-end iterator. */
63 basic_safe_iterator ()
66 value_type
operator* () const { return *m_it
; }
68 self_type
&operator++ ()
76 bool operator== (const self_type
&other
) const
77 { return m_it
== other
.m_it
; }
79 bool operator!= (const self_type
&other
) const
80 { return m_it
!= other
.m_it
; }
83 /* The current element. */
86 /* The next element. Always one element ahead of M_IT. */
89 /* A one-past-end iterator. */
93 #endif /* COMMON_SAFE_ITERATOR_H */