1/*
2 This file is part of libkdepim.
3
4 Copyright (c) 2005 Ingo Kloecker <kloecker@kde.org>
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library 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 GNU
14 Library General Public License for more details.
15
16 You should have received a copy of the GNU Library General Public License
17 along with this library; see the file COPYING.LIB. If not, write to
18 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 Boston, MA 02110-1301, USA.
20*/
21
22#ifndef __KMIME_KAUTODELETEHASH__
23#define __KMIME_KAUTODELETEHASH__
24
25#include <QtCore/QHash>
26
27namespace KMime {
28
29/**
30 * The KAutoDeleteHash class is a convenience QHash subclass that provides
31 * automatic deletion of the values in the destructor. Apart from this
32 * KAutoDeleteHash behaves exactly like QHash<Key, T *>.
33 *
34 * Since the automatic deletion is restricted to the destruction of the hash
35 * you have take care of the deletion of values you remove or replace yourself.
36 * To replace a value in the hash by another value use
37 * @code
38 * delete hash.take( key );
39 * hash.insert( key, value );
40 * @endcode
41 * and to remove a value from the hash use
42 * @code
43 * delete hash.take( key );
44 * @endcode
45 *
46 * @author Ingo Kl&ouml;cker \<kloecker@kde.org\>
47 */
48template <class Key, class T>
49class KAutoDeleteHash : public QHash<Key, T *>
50{
51public:
52 /**
53 * Constructs an empty hash.
54 */
55 KAutoDeleteHash() {}
56 /**
57 * Constructs a copy of @p other (which can be a QHash or a KAutoDeleteHash).
58 */
59 KAutoDeleteHash( const QHash<Key, T *> &other ) : QHash<Key, T *>( other ) {}
60
61 /**
62 * Destroys the hash and deletes all values. References to the values in the
63 * hash and all iterators of this hash become invalid.
64 */
65 ~KAutoDeleteHash() { while ( ! QHash<Key, T *>::isEmpty() ) {
66 T *value = *QHash<Key, T *>::begin();
67 this->erase( QHash<Key, T *>::begin() );
68 delete value;
69 }
70 }
71};
72
73} // namespace KMime
74
75#endif /* __KMIME_KAUTODELETEHASH__ */
76