1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 #ifndef INCLUDED_COMPHELPER_WEAKBAG_HXX
25 #define INCLUDED_COMPHELPER_WEAKBAG_HXX
26 
27 #include "sal/config.h"
28 
29 #include <list>
30 #include "com/sun/star/uno/Reference.hxx"
31 #include "cppuhelper/weakref.hxx"
32 #include "osl/diagnose.h"
33 
34 namespace comphelper {
35 
36 /**
37    A bag of UNO weak references.
38 */
39 template< typename T > class WeakBag {
40 public:
41     /**
42        Add a new weak reference.
43 
44        The implementation keeps the amount of memory consumed linear in the
45        number of living references added, not linear in the number of total
46        references added.
47 
48        @param e
49        a non-null reference.
50     */
add(com::sun::star::uno::Reference<T> const & e)51     void add(com::sun::star::uno::Reference< T > const & e) {
52         OSL_ASSERT(e.is());
53         for (typename List::iterator i(m_list.begin()); i != m_list.end();) {
54             if (com::sun::star::uno::Reference< T >(*i).is()) {
55                 ++i;
56             } else {
57                 i = m_list.erase(i);
58             }
59         }
60         m_list.push_back(com::sun::star::uno::WeakReference< T >(e));
61     }
62 
63     /**
64        Remove a living reference.
65 
66        @return
67        a living reference, or null if there are none.
68     */
remove()69     com::sun::star::uno::Reference< T > remove() {
70         while (!m_list.empty()) {
71             com::sun::star::uno::Reference< T > r(m_list.front());
72             m_list.pop_front();
73             if (r.is()) {
74                 return r;
75             }
76         }
77         return com::sun::star::uno::Reference< T >();
78     }
79 
80 private:
81     typedef std::list< com::sun::star::uno::WeakReference< T > > List;
82 
83     List m_list;
84 };
85 
86 }
87 
88 #endif
89