3 #ifndef SHARECONTAINER_H
4 #define SHARECONTAINER_H
9 #include <boost/utility.hpp>
10 #include <boost/smart_ptr.hpp>
12 /// Share objects between several users.
14 This class can be used to reduce memory consuption when you have a lot
15 of equal objects used all over your code.
17 \author Lars Gullik Bjønnes
20 class ShareContainer : boost::noncopyable {
23 typedef std::vector<boost::shared_ptr<Share> > Params;
25 typedef typename Params::value_type value_type;
26 /// Return a shared_ptr that points to a element equal to ps.
28 get(Share const & ps) const {
29 // First see if we already have this ps in the container
30 typename Params::iterator it = std::find_if(params.begin(),
34 if (it == params.end()) {
35 // ok we don't have it so we should
37 tmp.reset(new Share(ps));
38 params.push_back(tmp);
39 // We clean here. This can cause us to have
40 // some (one) unique elemements some times
41 // but we should gain a lot in speed.
44 // yes we have it already
46 // move it forward - optimization
47 // makes the next find faster.
48 if (it != params.begin())
49 std::swap(*it, *(it - 1));
54 /// A functor returning true if the elements are equal.
56 isEqual(Share const & s) : p_(s) {}
57 bool operator()(value_type const & p1) const {
58 return *p1.get() == p_;
63 /// A functor returning true if the element is unique.
65 bool operator()(value_type const & p) const {
70 /** Remove all unique items.
71 This removes all elements from params that is only referenced
72 from the private container. This can be considered a memory
76 typename Params::iterator it = std::remove_if(params.begin(),
79 params.erase(it, params.end());
82 /// The actual container.
83 mutable Params params;