3 #ifndef SHARECONTAINER_H
4 #define SHARECONTAINER_H
6 #include <boost/utility.hpp>
7 #include <boost/shared_ptr.hpp>
13 /// Share objects between several users.
15 This class can be used to reduce memory consuption when you have a lot
16 of equal objects used all over your code.
18 \author Lars Gullik Bjønnes
21 class ShareContainer : boost::noncopyable {
24 typedef std::vector<boost::shared_ptr<Share> > Params;
26 typedef typename Params::value_type value_type;
27 /// Return a shared_ptr that points to a element equal to ps.
29 get(Share const & ps) const {
30 // First see if we already have this ps in the container
31 typename Params::iterator it = std::find_if(params.begin(),
35 if (it == params.end()) {
36 // ok we don't have it so we should
38 tmp.reset(new Share(ps));
39 params.push_back(tmp);
40 // We clean here. This can cause us to have
41 // some (one) unique elemements some times
42 // but we should gain a lot in speed.
45 // yes we have it already
47 // move it forward - optimization
48 // makes the next find faster.
49 if (it != params.begin())
50 std::swap(*it, *(it - 1));
55 /// A functor returning true if the elements are equal.
57 isEqual(Share const & s) : p_(s) {}
58 bool operator()(value_type const & p1) const {
59 return *p1.get() == p_;
64 /// A functor returning true if the element is unique.
66 bool operator()(value_type const & p) const {
71 /** Remove all unique items.
72 This removes all elements from params that is only referenced
73 from the private container. This can be considered a memory
77 typename Params::iterator it = std::remove_if(params.begin(),
80 params.erase(it, params.end());
83 /// The actual container.
84 mutable Params params;